【问题标题】:Adding up contents of list - project euler 1添加列表的内容 - 项目 euler 1
【发布时间】:2015-01-22 18:29:10
【问题描述】:

我正在尝试在 Python (http://projecteuler.net./problem=1) 中执行 Project Euler 问题 1,并且我正在使用 while 循环循环到 1000:

from collections import Counter

x = 0
target = 1000
correctMultiples = list()
while x < target:
    x += 1
    if x % 3 == 0 or x % 5 == 0:
        correctMultiples.append(x)

print(str(correctMultiples) + ' are multiples of 3 or 5')

print('The sum of the multiples of 3 or 5 under 1000 is, ' + str(sum(correctMultiples))) # For some reason, 1000 over, answer is 233168 NOT 234168

这可行,但我得到的答案是 1000 以上。我得到 234168 而不是 233168。

我已尝试检查重复项:(在 How to find duplicate elements in array using for loop in Python? 之后)

duplicates = Counter(correctMultiples)
print([i for i in duplicates if duplicates[i] > 1])

但我不认为可以有重复,可以吗?因为我正在使用 if x % 3 or ...

我知道这不是最有效的方法,但仍然......为什么它不起作用? 谁能帮我找出答案为什么超过1000? 谢谢

【问题讨论】:

  • 提示:1000 能被 3 或 5 整除吗?
  • 值得注意的是,如果你想摆脱重复,你可以简单地list(set(myList))
  • 您可能还想查看range()

标签: python list python-3.x


【解决方案1】:

您在循环中包含1000,而问题要求 1000 以下的数字。

在这里你在做边界检查后递增,所以当x==999你仍然会运行循环:

while x < target:
    x += 1

使用for 循环会容易得多:

for x in range(1000):

range 是否包含最后一个元素。

【讨论】:

  • 抱歉,我是 Python 新手——当我说
  • 不,但是你增加x 之后你做那个检查。
【解决方案2】:

您在循环中包含数字 1000,因为在最后一次迭代中,x 是 999,并且会再次增加。

更好的解决方案是构造

for x in range(1,1000):
    ...

其中包括从 1 到 999 的所有 x,并且不会在每次迭代中与 1000 进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2018-06-18
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多