我刚刚完成Project Euler,问题没有。 1 for Python ...链接到下面:
http://projecteuler.net/problem=1
我想出了以下解决方案,在python ......
#!/usr/bin/env python
def main():
print("The answer will be calculated shortly...")
if __name__ == "__main__":
main()
n = 1000
n=-1
def isMultiple(i):
if (i % 3 == 0) or (i % 5 == 0):
if (i % 3 == 0) and (i % 5 == 0):
return False
else:
return True
sum = 0
for i in range(3, n):
if isMultiple(i):
sum+=1
print("The answer is... ", sum)
然而,在运行此解决方案时,所有这些都是:
[arch@archlinux Project Euler]$ python 1000-multi3or5.py
The answer will be calculated shortly...
[arch@archlinux Project Euler]$
我真的不明白出了什么问题,你能帮我解释一下原因吗?非常感谢您花时间阅读本文,特别是如果您不耐烦地帮助我。 :)
答案 0 :(得分:2)
因为循环永远不会发生:
n = 1000
n=-1
然后在结束时:
for i in range(3, n):
您正在运行范围从3到-1。
In [4]: range(3, -1)
Out[4]: []
将行更改为:
n -= 1
它应该有效:
In [9]: n = 20 # Just to show a smaller output - your n would be 999 obviously
...: sum = 0
...: for i in range(3, n):
...: if isMultiple(i):
...: sum+=1
...: print("The answer is... ", sum)
...:
('The answer is... ', 1)
('The answer is... ', 1)
('The answer is... ', 2)
('The answer is... ', 3)
('The answer is... ', 3)
('The answer is... ', 3)
('The answer is... ', 4)
('The answer is... ', 5)
('The answer is... ', 5)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 7)
('The answer is... ', 7)