Week 1 Introduction
Week 1 Introduction
PROGRAMMING,
DATA STRUCTURES AND
ALGORITHMS IN PYTHON
Week 1, Lecture 1
“Recipe”, or program
And more …
gcd(8,12) = 4
gcd(18,25) = 1
Example: gcd(14,63)
Factors of 14
1 2 3 4 5 6
1 7
2 8 14
7 9 10 11 12 13 14
Computing gcd(14,63)
Factors of 14 1 2 7 14
Factors of 63 1 2
3 3
7 …
9 21
7 63
… 9 … 21 … 63
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
PROGRAMMING,
DATA STRUCTURES AND
ALGORITHMS IN PYTHON
Week 1, Lecture 3
Then m = ad, n = bd
So m-n = ad - bd = (a-b)d
So gcd(m,n) = gcd(n,m-n)
Euclid’s algorithm
If n divides m, return n
if (m%n) == 0:
return(n)
else:
diff = m-n
# diff > n? Possible!
return(gcd(max(n,diff),min(n,diff))
Euclid’s algorithm, again
def gcd(m,n):
while (m%n) != 0:
diff = m-n
# diff > n? Possible!
(m,n) = (max(n,diff),min(n,diff))
return(n)
Even better
Suppose n does not divide m
Then m = ad, n = bd
So ad = q(bd) + r
If n divides m, return n
Return gcd(n,r)
Euclid’s algorithm
def gcd(m,n):
if (m%n) == 0:
return(n)
else:
return(gcd(n,m%n)) # m%n < n, always!
Euclid’s algorithm, revisited
def gcd(m,n):
while (m%n) != 0:
(m,n) = (n,m%n) # m%n < n, always!
return(n)
Efficiency
PROGRAMMING,
DATA STRUCTURES AND
ALGORITHMS IN PYTHON
Week 1, Lecture 4
Python 2.7
Go for it!