red*_*use 4 python greatest-common-divisor
我想为数字列表计算gcd。但是我不知道我的代码有什么问题。
A = [12, 24, 27, 30, 36]
def Greatest_Common_Divisor(A):
for c in A:
while int(c) > 0:
if int(c) > 12:
c = int(c) % 12
else:
return 12 % int(c)
print Greatest_Common_Divisor(A)
Run Code Online (Sandbox Code Playgroud)
big*_*nty 14
从 python 3.9 开始,python 获得了对数字列表计算 gcd 的内置支持。
import math
A = [12, 24, 27, 30, 36]
print(math.gcd(*A))
Run Code Online (Sandbox Code Playgroud)
输出:
3
Run Code Online (Sandbox Code Playgroud)
小智 9
def gcd (a,b):
if (b == 0):
return a
else:
return gcd (b, a % b)
A = [12, 24, 27, 30, 36]
res = A[0]
for c in A[1::]:
res = gcd(res , c)
print res
Run Code Online (Sandbox Code Playgroud)
小智 8
这是我使用的一段代码:
from fractions import gcd
from functools import reduce
def find_gcd(list):
x = reduce(gcd, list)
return x
Run Code Online (Sandbox Code Playgroud)
小智 5
我使用了这段代码:
def gcd(my_list):
result = my_list[0]
for x in my_list[1:]:
if result < x:
temp = result
result = x
x = temp
while x != 0:
temp = x
x = result % x
result = temp
return result
Run Code Online (Sandbox Code Playgroud)
如果您想使用现有方法,请尝试“np.gcd.reduce”:
import numpy as np
A = [12, 24, 27, 30, 36]
print(np.gcd.reduce(A))
Run Code Online (Sandbox Code Playgroud)
返回3
归档时间: |
|
查看次数: |
14617 次 |
最近记录: |