Search code examples
pythonnested-loops

How can I avoid "IndentationError: too many levels of indentation" from deeply nested for loops?


I am doing a Project Euler question for programming practice in order to self-teach myself. I know perfectly well how to do the question mathematically, as well as how to do it programmatically.

However, I have to have come up with some insane code to do it; 100 nested loops and Python hilariously raises this error, and probably rightfully so, on 100 levels of indentation:

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

I have looked through google for solutions but this issue is so rare it has almost no literature on the subject and I could only find this other stack overflow question ( Python IndentationError: too many levels of indentation ) which I could not find much useful in for my question.

My question is - is there a way to take my solution and find some workaround or refactor it in a way that has it work? I am truly stumped.


Solution

  • A recursive solution should do nicely, though I'm certain there is an entirely different solution to the problem that doesn't require this kind of manipulation.

    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)
    

    Interestingly enough, if you memoize this function, it will actually have a reasonable running time (such is the power of dynamic programming). Have fun!