Phython_Week1
Phython_Week1
'''
'''
def gcd(m,n):
"""docstring for gcd"""
# TODO: write code...
fm = []
for i in range(1,m+1):
if (m%i) == 0:
# TODO: write code...
fm.append(i)
fn = []
for j in range(1,n+1):
if (n%j) == 0:
# TODO: write code...
fn.append(j)
cf = []
for k in fm:
if k in fn:
cf.append(k)
# below code returns right most number from the list
return(cf[-1])
print("Hello World")
m=63
n=9
print(gcd(m,n))
2> Improve coed for for gcd instead of having multipl loops..replaced with single
loop
def gcd(m,n):
"""docstring for gcd"""
# TODO: write code...
cf = []
for i in range(1, min(m,n)+1):
#print(i)
if (m%i) == 0 and (n%i) == 0:
# TODO: write code...
cf.append(i)
#print(i)
return(cf[-1])
print("Hello World")
m=63
n=9
print(gcd(m,n))gcd algorithm
def gcd(m,n):
"""docstring for gcd"""
# TODO: write code...
factorLatest = 1
for i in range(1, min(m,n)+1):
#print(i)
if (m%i) == 0 and (n%i) == 0:
# TODO: write code...
factorLatest=i
#print(i)
return(factorLatest)
print("Hello World")
m=63
n=9
print(gcd(m,n))
def gcd(m,n):
"""docstring for gcd"""
# TODO: write code...
factorLatest = 1
i=min(m,n)
while i>0:
# TODO: write code...if
if (m%i) == 0 and (n%i) == 0:
return(i)
else:
i=i-1
print("Hello World")
m=63
n=9
print(gcd(m,n))
m=1
n=3
(m,n)=(n,m)
#after above step m =3 and n= 1
inthe
def gcd(m,n):
"""gcd by using recursion"""
# Here assumption is that m is always greater than n
# TODO: write code...
if (m<n):
(m,n)=(n,m)
if(m%n) == 0:
return(n)
else:
diff = m-n
gcd(max(n,diff), min(n,diff))
print("Hello World")
m=63
n=9
print(gcd(m,n))
def gcd(m,n):
"""gcd by using recursion"""
# Here assumption is that m is always greater than n
# TODO: write code...
if (m<n):
(m,n)=(n,m)
while (m%n) != 0:
diff = m-n
(m,n) = (max(n,diff), min(n,diff))
return(n)
print("Hello World")
m=63
n=9
print(gcd(m,n))
QUIZ>
Week 1 Quiz
ans: 6
h(36)
: 36%2
s =2
s = 2+3
s = 5+4
s = 9+6
s= 15+9
s = 24+12
s = 36+18
s = 54 +
h(34)
s = 2
s = 2+17
s = 19 +
Ans: 35
For what value of n would g(637,n) return 4? If there are multiple possibilities,
write any one.
def g(m,n):
res = 0
while m >= n:
(res,m) = (res+1,m/n)
return(res)
5
ANs:5