I am trying to use Euclid's algorithm to calculate the gcd of a list using Python 3. However, I get the error "TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'". I checked everywhere, but still can not find what's wrong with my code. Here is my code,
# To get the gcd of a list
def gcd(numbers):
m = numbers[0]
for i in range(1, len(numbers)):
m = gcd2(m, numbers[i])
return m
# Use Euclid’s algorithm to calculate the gcd of two numbers
def gcd2(m, n):
if m % n != 0:
gcd2(n, m % n)
else:
return n
def main():
str = [44, 6, 12, 24, 4, 18]
print(gcd(str))
main()
You are missing a return statement on line 3 of gcd2. The updated function is below.
def gcd2(m, n):
if m % n != 0:
return gcd2(n, m % n)
else:
return n
Hope this helps.
def gcd2(m, n):
if m % n != 0:
gcd2(n, m % n)
else:
return n
In the if
You aren't returning anything, so it defaults to None
. Add return there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.