简体   繁体   English

使用Python 3和Euclid算法计算列表的gcd

[英]Using Python 3 and Euclid’s algorithm to calculate the gcd of a list

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'". 我正在尝试使用Euclid算法使用Python 3计算列表的gcd。但是,出现错误“ TypeError:%不支持的操作数类型:'NoneType'和'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. 您缺少gcd2第3行上的return语句。 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 . if您不返回任何内容,则默认为None Add return there. 在此添加返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM