我正在做一個Project Euler編程實踐的問題,以便自我教導自己。我非常清楚如何在數學上做這個問題,以及如何以編程的方式做到這一點。Python IndentationError - 如何重構?
但是,我必須想出一些瘋狂的代碼來做到這一點; 100個嵌套循環和Python歡快提出了這個錯誤,而且很可能是理所當然的,在100個級別的縮進:
IndentationError: too many levels of indentation
tally = 0
ceiling = 100
for integer_1 in range(0, 100, 1):
for integer_2 in range(0, 100 - integer_1, 2):
for integer_3 in range(0, 100 - integer_1 - integer_2, 3):
for integer_4 ....
for integer_5 ....
etc.
etc.
all the way to integer_100
我已經通過谷歌尋找解決方案,但這個問題是如此罕見,它幾乎沒有文學的主題和我只能找到這個其他堆棧溢出問題(Python IndentationError: too many levels of indentation),我無法找到對我的問題很有用的問題。
我的問題是 - 有沒有辦法讓我的解決方案,並找到一些解決方法或重構它的方式,它的工作?我真的很難過。
編輯:
由於nneonneo的回答,我是能夠解決的問題。我的代碼僅供將來參考,用於尋找正確重構代碼的方法。
from time import time
t = time()
count_rec_dict = {}
# for finding ways to sum to 100
def count_rec(cursum, level):
global count_rec_dict
# 99 is the last integer that we could be using,
# so prevent the algorithm from going further.
if level == 99:
if cursum == 100:
return 1
else:
return 0
res = 0
for i in xrange(0, 101-cursum, level+1):
# fetch branch value from the dictionary
if (cursum+i, level+1) in count_rec_dict:
res += count_rec_dict[(cursum+i, level+1)]
# add branch value to the dictionary
else:
count_rec_dict[(cursum+i, level+1)] = count_rec(cursum+i, level+1)
res += count_rec_dict[(cursum+i, level+1)]
return res}
print count_rec(0, 0)
print time() - t
它在我的電腦上以驚人的0.041秒運行。哇!!!!!今天我學到了一些新東西!
射擊 - 對不起,我在範圍內有一個錯誤。現在修復 – nebffa
只需要說,如果你有100個嵌套循環,那就應該有更好的方法... – Claudiu
這看起來很蠻橫,而且無論哪個歐拉問題,我敢打賭有一個更聰明的方法來做它。很多這些問題都基於數學見解。 – wim