[英]Find max value in for loop range - Python
I've been working on a small program that takes the input of two numbers and gives the greatest common divisor. 我一直在研究一个小程序,该程序接受两个数字的输入并给出最大的公约数。 I have managed to get the program to at least print out all common divisors until the greatest number is reached, but all I need to print is the max value. 我设法使程序至少打印出所有常用除数,直到达到最大数为止,但是我需要打印的只是最大值。 Unfortunately, I can't get seem to get this to work. 不幸的是,我似乎无法使它正常工作。 I've tried passing i though max() but was received an error that ''int' objects are not iterable''. 我试图通过max()传递给我,但是收到一个错误消息,提示“ int”对象不可迭代。 Thus I am wondering if anyone could help me find a solution that will allow me to print only the max value as opposed to all values without having to employ much more complex coding methods. 因此,我想知道是否有人可以帮助我找到一个解决方案,使我可以仅打印最大值而不是所有值,而不必采用更复杂的编码方法。 Here is the code 这是代码
def great_divisor():
m = int(raw_input("Choose a number"))
n = int(raw_input("Choose another number"))
#lowest number assigned to d
if m > n:
d = n
else:
d = m
for i in range(1, d + 1):
if (n%i == 0 and m%i == 0):
print(max(i))
return
The easiest way is to use range(d, 0, -1)
and just return the first divisor you find. 最简单的方法是使用range(d, 0, -1)
并仅返回找到的第一个除数。 No need to use max
. 无需使用max
。
Max can only be applied to an iterable, a list for example. Max只能应用于可迭代对象,例如列表。
You can add all the common divisor in a list and get the max. 您可以在列表中添加所有公共除数并获得最大值。
for i in range(1, d + 1):
if (n%i == 0 and m%i == 0):
divisors.append(i)
print(max(divisors))
How about this? 这个怎么样?
maxn = 0
for i in range(1, d + 1):
if (n%i == 0 and m%i == 0):
maxn = i
return maxn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.