Miles Black
Miles Black

Reputation: 3

Why my outer loop doesn't carry on once my inner recursion has finished?

I am currently doing p24 of ProjectEuler, and trying to print all of the permutations of a list as a way to begin solving the problem, eg an input [0,1,2] will print 0,1,2,0,2,1,1,0,2,1,2,0,2,0,1,2,1,0.

I have written this python code:

def perms(my_list):

    for i in my_list:

        print(i)

        new_list = my_list
        new_list.remove(i)

        if len(new_list)>0:
            print("new list:", new_list)
            perms(new_list)

my_list = [0,1,2]
perms(my_list)    

However this only outputs:

0 #(from the loop in the top layer of the function)
1 #(from the loop in the recursion a layer below)
2 #(from the loop 2 layers below)

But it then stops, instead of carrying on with the loop in the top layer of the function (instead of carrying on with the next term in the list, 1). Have I made a logic error, because I thought that once any inner recursions were finished, the program should return to the recursion layer above that and carry on as normal.

How could I get it to output the following?:

0
1
2
1
0
2
...
2
1
0

Thank you for reading ;)

Upvotes: 0

Views: 49

Answers (1)

Arpit Parmar
Arpit Parmar

Reputation: 300

NOTE: I'm not providing the actual solution to the problem you are solving instead just answering the question why your recursion ended earlier.

The problem lies in the line 4 where you are not cloning the list but assigning the reference of one list to another. Basically new_list is pointing to the same list that my_list is pointing to. To clone a list there are many ways to do so. One of them is as follows:

new_list = my_list[:]

You can checkout other ways here: https://www.google.com/amp/s/www.geeksforgeeks.org/python-cloning-copying-list/amp/

Upvotes: 1

Related Questions