1

So basically I'm trying to take a list of numbers and write a recursive function that outputs all possible outputs in a list of lists.

My code:

def permutations(lst):
    if len(lst) <= 1:
        return lst
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remlst = lst[:i] + lst[i+1:]
        for p in permutations(remlst):
            l.append([m] + p)
        return l

I'm getting a few errors about not being able to append int.

Simple output:

>>>permutations([1,2])
[[1,2],[2,1]]
1
  • give us a stacktrace :) Commented Mar 14, 2017 at 2:22

2 Answers 2

3

There is an implementation for that in itertools:

import itertools
for p in itertools.permutations(list):
   # do stuff

Also, to fix your own function, notice that in your "base case" len(lst) <= 1 your returning a list, instead of a list-of-lists. Also, the second return statement should be moved out of the loop;

def permutations(lst):
    if len(lst) <= 1:
        return [lst]
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remlst = lst[:i] + lst[i+1:]
        for p in permutations(remlst):
            l.append([m] + p)
    return l
Sign up to request clarification or add additional context in comments.

Comments

0

Because you iterate through result of permutations

for p in permutations(remlst):

your base case needs to return a list of lists like your recursive case does, otherwise you get the error TypeError: can only concatenate list (not "int") to list

You also need to return after the outer for loop.

def permutations(lst):
    if len(lst) <= 1:
        return [lst] # [[X]]
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remlst = lst[:i] + lst[i+1:]
        for p in permutations(remlst):
            l.append([m] + p)
    return l # return at end of outer for loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.