加上小于1000的3和5的倍数

2024-04-24 23:23:04 发布

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

我在试着求3和5的倍数之和,而总和小于1000。当我运行代码时,我得到的是一个永不结束的0列表,它说“要处理的输出太多”。我不知道我哪里出了问题,希望能得到反馈。你知道吗

result = 0
while result <= 1000:
    i = 0
    if i % 3 == 0 or i % 5 == 0:
        print i
        result += i
else:
    i += 1

编辑

循环每次都将i重置为0。这意味着它总是小于1000。你知道吗


Tags: or代码编辑列表ifresultelse重置
3条回答

你从不增加i,把i=0放在循环外,把i+=1放在循环内。i、 e

result = 0
i = 0

while result <= 1000:
    if i % 3 == 0 or i % 5 == 0:
        print(i)
        result += i
    i += 1

一个有趣的练习是用一种更“pythonic”的方式重写它,例如:

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

或者更好:

sum(x for x in xrange(1000) if x % 3 == 0 or x % 5 == 0)

结果都是233168。你知道吗

(请注意,在这两种情况下sum()都是Python内置函数)。你知道吗

顺便说一下,在问题陈述中,您提到了“少于1000”,但您的代码在循环中包含1000。你知道吗

你有一个无限循环,因为i不是递增的,而且result。你知道吗

然后归结为你到底想要什么:

总和小于1000

result = 0
i = 0 
while result <= 1000:
    i += 1
    if i % 3 == 0 or i % 5 == 0:
        result += i

print(result - i)
# 998

元素小于1000

如果您引用的是Euler problem,那么总和不应小于1000,但是元素:

total_sum = 0
for i in range(1000):
    if (i % 3 == 0 or i % 5 == 0):
        total_sum = total_sum + i
print total_sum  
# 233168

另一种选择是:

sum(set(range(0,1000,3)) | set(range(0,1000,5)))
# 233168

或:

sum(range(0,1000,3)) + sum(range(0,1000,5)) - sum(range(0,1000,15))
# 233168

相关问题 更多 >