
February 17th, 2013, 05:24 PM
|
 |
Contributing User
|
|
|
|
First, change gcd to return the greatest common divisor rather than print it. Almost always better to return a value than print it. You can print it later. In this case it's necessary.
Code:
def gcd(a, b):
while b != 0 :
a, b = b, a%b
return a
Next, compute the gcd over a list of numbers as
Code:
import functools
functools.reduce(gcd, [24, 6, 60])
Computing in turn the gcd of 24 and 6 which is 6, then of 6 and 60 which is 6. Now you've got conceptually correct code for any size list.
__________________
[code] Code tags[/code] are essential for python code!
|