0

I am doing an exercise to print out all the permutations of [0,1,2,3]. And the output is supposed to be in the same form, like [2,3,1,0] for example. I wrote down the following code.

def permutations(units):
    permutation_list = []
    if len(units) == 1:
        return units
    else:
        for i in units:
            new = [j for j in units if j != i]
            [permutation_list.append([i] + p) for p in permutations(new)]
    return permutation_list

print(permutations([0,1,2,3]))

However, it gives me an error saying that p is int and that list [i] and int p can not be added.

units is list and output is a list so I don't understand how p can be int. Any clarification would be very much appreciated.

Edit. This is the error I get:

[permutation_list.append([i] + p) for p in permutations(new)]

TypeError: can only concatenate list (not "int") to list

Buhiii
  • 1
  • 1
  • 2
    "However, it gives me an error saying that p is int and that list [i] and int p can not be added." If you are getting an error, **please post the full error message including the stack trace**. – juanpa.arrivillaga Nov 07 '22 at 22:39
  • 3
    As an aside, `[permutation_list.append([i] + p) for p in permutations(new)]` is *not* how you should be using list comprehensions. Do *not* use list comprehensions for side effects, just use a regular for-loop – juanpa.arrivillaga Nov 07 '22 at 22:39
  • 1
    Your issue is that when you reach the last unit and you call `permutrations([3])` you will be returned `[3]` which you then iterate over this list. I.E p will be set to the int value of `3` – Chris Doyle Nov 07 '22 at 22:41
  • 1
    Anyway, `units` is always a list of integers. When you hit the base case, `permutations` returns a list with a single integer. You then try to do `permutation_list.append([i] + p) for p in permutations(new)` where `p` is that single integer, hence the error – juanpa.arrivillaga Nov 07 '22 at 22:42
  • @juanpa Reference for that: [list comprehension for side effects](/a/5753614/4518341) – wjandrea Nov 07 '22 at 22:42
  • 2
    you need to change your base case to return a list of lists `return [units]` to fit your current code – Chris Doyle Nov 07 '22 at 22:44

0 Answers0