Python Week1 Lecture2 Handout
Python Week1 Lecture2 Handout
PROGRAMMING,
DATA STRUCTURES AND
ALGORITHMS IN PYTHON
Week 1, Lecture 2
def gcd(m,n):
cf = []
for i in range(1,min(m,n)+1):
if (m%i) == 0 and (n%i) == 0:
cf.append(i)
return(cf[-1])
Do we need lists at all?
We only need the largest common factor
def gcd(m,n):
for i in range(1,min(m,n)+1):
if (m%i) == 0 and (n%i) == 0:
mrcf = i
return(mrcf)
Scan backwards?
def gcd(m,n):
i = min(m,n)
while i > 0:
if (m%i) == 0 and (n%i) == 0:
return(i)
else:
i = i-1
A new kind of repetition
while condition:
step 1
step 2
. . .
step k