不太熟悉 while 循环,但我认为它是一种替代方法,所以这可能是一个基本错误。
我需要寻找 1000 以下的自然数之和,它们是 3 和 5 的倍数。例如,10 以下
multiples of 3 and 5 < 10 = 3,5,6,9
sum = 23
我使用 for 循环的代码如下(这是我最初的解决方案):
def multiple():
lst = []
for x in range(334): #didn't know how else to use a for loop but to find the largest value of x using a calculator
if 3*x < limit:
lst.append(3*x)
if 5*x< 1000:
lst.append(5*x)
if (3*x > 1000) and (5*x > 1000): #unnecessary in a forloop with a range but this is just to maintain symmetry with while loop
break
lst2 = list(set(lst)) #remove duplicates
print(sum(lst2))
multiple()
我的代码使用了一个 while 循环(这个解决方案甚至没有出现在控制台中 --> 也许这是错误所在):
def multiple():
lst = []
while True:
x = 1
if 3*x < 1000:
lst.append(3*x)
if 5*x< 1000:
lst.append(5*x)
if (3*x > 1000) and (5*x > 1000):
break
x += 1
lst2 = list(set(lst)) #remove duplicates
print(sum(lst2))
multiple()
期望的输出:
233168
除了如何纠正while循环之外,任何对我的for循环或while循环的改进也将受到欢迎。谢谢
最佳答案
严格调试
由于您是新手,让我们借此机会在解决错误之前先对其进行分析。首先请注意,您根本没有注意到任何打印输出。因此,您的 print()
语句要么没有运行,要么只打印空格。我们可以排除后者,因为 sum() 将返回一个整数。
因此,print()
永远不会运行。该函数已正确定义和调用,所以这不是问题。现在注意 while True:
;这是一个预警信号。如果 while 循环永不结束,则 print()
将永远不会运行。我们确实注意到有多个 break
语句应该停止循环,但它们很可能存在问题。
现在我们检查循环是如何更新的。首先,注意 i+=1
。这似乎是正确的。但是,i=1
也在 while 循环中。这不可能是正确的,因为每次迭代 i
都会被重置。这将导致循环永远运行。
这种对代码的批判性分析只能通过实践建立,但希望这个答案能让您深入了解如何自己解决这个问题(以及我如何查看您的代码)。
另请注意,将 print 语句添加到 while 循环中进行测试会让您注意到 i
始终为 1。
工作代码
def multiple():
lst = []
x = 1 # moved from line below
while True:
# x = 1 should not go here
if 3*x < 1000:
lst.append(3*x)
if 5*x< 1000:
lst.append(5*x)
if (3*x > 1000) and (5*x > 1000):
break
x += 1
lst2 = list(set(lst)) #remove duplicates
print(sum(lst2))
multiple()
关于python - while 循环 vs for 循环求 3 和 5 的倍数之和小于 1000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47965782/