python - Euclidean algorithm (GCD) with multiple numbers? -
so i'm writing program in python gcd of amount of numbers.
def gcd(numbers): if numbers[-1] == 0: return numbers[0] # i'm stuck here, wrong in range(len(numbers)-1): print gcd([numbers[i+1], numbers[i] % numbers[i+1]]) print gcd(30, 40, 36)
the function takes list of numbers. should print 2. however, don't understand how use the algorithm recursively can handle multiple numbers. can explain?
updated, still not working:
def gcd(numbers): if numbers[-1] == 0: return numbers[0] gcd = 0 in range(len(numbers)): gcd = gcd([numbers[i+1], numbers[i] % numbers[i+1]]) gcdtemp = gcd([gcd, numbers[i+2]]) gcd = gcdtemp return gcd
ok, solved it
def gcd(a, b): if b == 0: return else: return gcd(b, % b)
and use reduce, like
reduce(gcd, (30, 40, 36))
since gcd associative, gcd(a,b,c,d)
same gcd(gcd(gcd(a,b),c),d)
. in case, python's reduce
function candidate reducing cases len(numbers) > 2
simple 2-number comparison. code this:
if len(numbers) > 2: return reduce(lambda x,y: gcd([x,y]), numbers)
reduce applies given function each element in list, like
gcd = reduce(lambda x,y:gcd([x,y]),[a,b,c,d])
is same doing
gcd = gcd(a,b) gcd = gcd(gcd,c) gcd = gcd(gcd,d)
now thing left code when len(numbers) <= 2
. passing 2 arguments gcd
in reduce
ensures function recurses @ once (since len(numbers) > 2
in original call), has additional benefit of never overflowing stack.
Thanks for posting this, Keep Sharing good content.
ReplyDeletePython Online Training
Data Science Online Training