Project Euler Exercise 1

2024-04-24 14:33:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出所有小于1000的数之和可以被3和5整除。到目前为止我有:

for i in range(0, 1000):
    if i % 3 == 0:
        print i
    elif i % 5 == 0:
        print i
b = sum(i)
print b

我得到一个TypeError: 'int' object is not iterable(指b = sum(i)


Tags: inforifobjectisnotrangeiterable
3条回答

你可以这样做:

# initially we declare a variable that will hold the current sum
# and at the end of the for it will hold 
# the sum of the numbers you have mentioned.
b = 0
for i in range(1000):
    # Then whether i is evenly divided by 3 or 5 
    # we add this number to the current sum
    if i % 3 == 0 or i % 5 == 0:
        b += i

# last we print the sum
print b

从您的代码中,我想您需要可以被3 or 5整除的数的总和。在所有解决方案中,另一种可能的单线性解决方案是:

print(sum(filter(lambda x: x%3==0 or x%5==0, range(1000))))

这里您得到这个TypeError,因为sum函数接受一个数字序列并返回序列的和。在您的代码中,传递i作为sum的参数,在您的例子中,它是一个int类型的对象。所以你得到了这个错误。你知道吗

使用以下行

sum以iterable对象作为输入。列表、集合等是可编辑的。你知道吗

所以试试下面的方法

b = sum(i for i in range(1000) if i%3 == 0 or i%5 == 0)

相关问题 更多 >