x = int(input("Pick one small number: "))
y = int(input("And a bigger number: "))
if x > y:
print ("Doesn't work. ")
elif x < y:
for i in range(x,y):
if i%7 == 0 and i%5 !=0:
z = sum(i)
print (z)
答案 0 :(得分:0)
您可能想一次将i
求和:
z = 0
for n in range(x,y):
if n%7 == 0 and n%5 !=0:
n += i
print("Running total:", z)
print("Final total:", z)
如果您想使用sum
,则必须将其应用于列表:
filtered_list = []
for n in range(x,y):
if n % 7 == 0 and n % 5 !=0:
filtered_list.append(n)
print("Final total:", sum(filtered_list))
或使用生成器表达式:
print(sum(n for n in range(x, y) if n%7 == 0 and n%5 !=0))
还有一种快捷方式来获取range(x, y)
中7的所有倍数:
multiples = range(x + 7 - x % 7, y, 7)
然后,您只需要检查第二个条件(不能被5整除)
print(sum(n for n in multiples if n%5 !=0))
您还可以创建2套并计算差值:
def multiples(start, stop, d):
""" This function returns the set of all multiples of d between start and stop """
return set(range(start + divisor - start % divisor, stop, divisor))
print(sum(multiples(x, y, 7) - multiples(x, y, 5))
最后是一种数学方法。您的if
条件是选择7的倍数并过滤掉5和7的倍数的数字。这等效于减去5和7的最小公倍数(即35)的倍数之和。 )从范围内7的倍数之和...
# we need a function from the math module that calculates the greatest common denominator
# we will use this to help calculate the least common multiple
from math import gcd
def sum_of_multiples(start, stop, mult):
""" Calculate sum of multiples of mult that lie in the range start, stop """
start //= mult
stop //= mult
return mult * (stop - start) * (stop + start + 1) / 2
lcm = 5 * 7 // gcd(5, 7) # The least common multiple of 5 and 7 = 35
print("Total:", sum_of_multiples(x, y, 7) - sum_of_multiples(x, y, lcm))
(当然,在上面您可以只写35而不是lcm
。如果您要使用其他数字应用此方法,我将给出计算结果。)
答案 1 :(得分:0)
您之所以遇到该异常,是因为sum期望一个可以被迭代的对象,或者换句话说,可以返回一个迭代器,例如列表或元组。
一种适当的方法是利用range函数返回的迭代器对象来获取x和y之间所有数字的累加值,这些数字是7的因数,而不是5的因数。
x = int(input("Pick one small number: "))
y = int(input("And a bigger number: "))
if x > y:
print ("Doesn't work. ")
elif x < y:
print(sum([i for i in range(x, y) if i%7 == 0 and i%5 != 0]))