Python IndentationError - 如何重构?

neb*_*ffa 4 python nested-loops

我正在为编程实践做一个项目欧拉问题,以便自我教学.我非常清楚如何以数学方式解决问题,以及如何以编程方式进行.

但是,我必须提出一些疯狂的代码才能做到这一点; 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
Run Code Online (Sandbox Code Playgroud)

我已经通过谷歌寻找解决方案,但这个问题是如此罕见,它几乎没有关于这个主题的文献,我只能找到这个其他堆栈溢出问题(Python IndentationError:太多级别的缩进),我找不到很多有用的我的问题.

我的问题是 - 有没有办法采取我的解决方案,找到一些解决方法或以一种有效的方式重构它?我真的很难过.

编辑:

感谢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
Run Code Online (Sandbox Code Playgroud)

在我的电脑上以惊人的0.041秒运行.哇!!!!!我今天学到了一些新东西!

nne*_*neo 5

递归解决方案应该做得很好,但我确信对于不需要这种操作的问题有一个完全不同的解决方案.

def count_rec(cursum, level):
    if level == 100:
        return 1
    res = 0
    for i in xrange(0, 100-cursum, level+1):
        res += count_rec(cursum+i, level+1)
    return res

print count_rec(0, 0)
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果你记住这个功能,它实际上会有一个合理的运行时间(这就是动态编程的强大功能).玩得开心!

  • 对,所以肯定有更好的方法:) (2认同)