Home > Back-end >  N nested for loops in a python
N nested for loops in a python

Time:10-23

I want N number of nested for loops, the last for loop should have number = 1 while everything else should have push(move) and should end with a undo() I saw a way to solve in another language that said something about recursion.

The following example if for 5 for loops:

number = 0
for move in all_legal_moves():
    push(move)
    for move2 in all_legal_moves():
        push(move2)
        for move3 in all_legal_moves():
            push(move3)
            for move4 in all_legal_moves():
                push(move4)
                for move5 in all_legal_moves():
                    number  = 1
                undo()
            undo()
        undo()
    undo()

I want a function that takes the depth (the number of nested for loops (N)) and return number. I would prefer an answer that doesn't imports any libraries

CodePudding user response:

Recursion is simply a function keeps calling itself until it meets certain condition. You can learn more here. I think in this case you can make the code above recursive by having it either push go to another recursion level undo or number = 1 by checking if the current loop level (level in the code below) is equal to N (max_level in the code below)

number = 0

def moves(level, max_level):
    global number
    if level < max_level:
        for move in all_legal_moves():
            push(move)
            moves(level   1, max_level)
            undo()
    else:
        number  = 1


moves(move, 1, 5)
print('Number of possible moves:', number)

Or if you don't want to have number as a global variable, you can make the function return the number of possible iterations instead

def moves(level, max_level):
    number = 0
    if level < max_level:
        for move in all_legal_moves():
            push(move)
            number  = moves(level   1, max_level)
            undo()
    else:
        number  = 1
    return number

number_of_possible_moves = moves(move, 1, 5)
print('Number of possible moves', number_of_possible_moves)
  • Related