[英]While loop running once?
編碼新手,正在嘗試解決該編碼問題以供學習。
提示:
如果我們列出所有低於10的自然數,這些自然數是3或5的倍數,則得到3、5、6和9。這些倍數的總和為23。找到低於1000的3或5的所有倍數的總和。
three = []
five = []
def threeList():
n = 1
while (n*3<1000):
result = n*3
three.append(result)
n += 1
return three
def fiveList():
n = 1
while (n*5<1000):
result = n*5
five.append(result)
n += 1
return five
threeList()
fiveList()
print(three,five)
這樣將在控制台上打印[3] [5]。
您的return
是循環的一部分,這意味着在迭代結束時,您只需從函數中return
,而不是進行另一次迭代。 將其移出循環,即:
def threeList():
n = 1
while (n*3<1000):
result = n*3
three.append(result)
n += 1
return three
同樣,這種return
沒有意義,因為您正在返回全局變量。 沒有意義返回已經可用的東西(我建議您閱讀有關變量scope的內容 ),因此完全擺脫這些return
是安全的:
def threeList():
n = 1
while (n*3<1000):
result = n*3
three.append(result)
n += 1
實際上,由於兩個函數的差異很小,因此您應該重構代碼,只有一個函數接受乘數(因為這是唯一的區別)並返回填充列表。 這次我們使用局部變量來創建結果列表,因此這一次您需要return
它,否則result
列表將在函數之外不可用:
def my_func(multiplier):
result = []
n = 1
while (n*multiplier < 1000):
result.append(n*multiplier)
n += 1
return result
然后更換
threeList()
fiveList()
與
three = my_func(3)
five = my_func(5)
實際上,您可以將它與print()
合並,因為three
和five
沒有其他用途,因此您的最終代碼將如下所示:
def my_func(multiplier):
result = []
n = 1
while (n*multiplier < 1000):
result.append(n*multiplier)
n += 1
return result
print(my_func(3), my_func(5))
除了Marcin出色的答案外,請注意,您還可以提前算出要使用哪些元素的數學運算,並完全避免while
循環。 range
是你的朋友在這里。
multiples_of_five = range(5, 1001, step=5)
multiples_of_three = range(3, 1001, 3)
由於range
的止損是獨占的 ,但我們希望3和5的所有倍數最多達到1000( 含) ,因此我們必須停在1001
。 這簡化了Marcin在上面放置的my_func
。
def list_multiples(n):
result = []
for i in range(n, 1001, n):
result.append(i)
return result
盡管如果我們仔細研究一下,您會發現我們基本上只是在投射到列表並返回。 讓我們直接這樣做。
def list_multiples(n):
return list(range(n, 1001, n))
從那里我們可以找到5的倍數和3的倍數
fives = list_multiples(5)
threes = list_multiples(3)
投射到set
到刪除重復(15既是5和3的倍數,但是不應當被相加兩次)
all_nums = set(fives + threes)
並對結果求和
result = sum(all_nums)
要以Python方式解決問題,請將sum()
與生成器表達式結合使用,例如:
sum(i for i in range(1000) if i % 5 == 0 or i % 3 == 0)
max_num = 1000
print(sum(i for i in range(max_num) if i % 5 == 0 or i % 3 == 0))
233168
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.