0

I am trying to generate a permutation of list in python with recursion.

import copy

def perm(seq):
    if len(seq) == 1:
        return seq
    else:
        nseq = perm(seq[1:])
        return zip_letter(seq[0], nseq)


def zip_letter(c, seq):
    lis = []
    for i in range(len(seq)+1):
        seq.insert(i, c)
        lis.append(copy.deepcopy(seq))
        seq.pop(i)
    return lis

print perm(['a', 'b', 'c'])

The output is [['a', ['b', 'c'], ['c', 'b']], [['b', 'c'], 'a', ['c', 'b']], [['b', 'c'], ['c', 'b'], 'a']]

which seems fine, but not in correctly inserted format. what am i missing?

1
  • 1
    Unless you are deliberately rewriting it yourself as an exercise, you should instead use itertools.permutations. Commented Feb 16, 2015 at 20:55

1 Answer 1

3

I would recommend using the existing function in itertools

>>> list(itertools.permutations(['a', 'b', 'c']))
[('a', 'b', 'c'),
 ('a', 'c', 'b'),
 ('b', 'a', 'c'),
 ('b', 'c', 'a'),
 ('c', 'a', 'b'),
 ('c', 'b', 'a')]
Sign up to request clarification or add additional context in comments.

5 Comments

I like itertools too, but this doesn't explain how to generate a permutation with recursion or point out the bug in the OP's code..
I want to use recursion. Not an existing library
@manishkumar: In that case, you should have explicitly stated in your question that you know about itertools.permutations but that you are doing it this way in order to learn about recursion. But your question probably would have still been closed, as there are good examples of recursion in the dupe link that's been add to your question. Also see Python recursion permutations.
@manishkumar: FWIW, it's best to avoid recursion in Python, unless you really need it. Python doesn't have tail call optimization, and there's a limit on recursion depth (although that can be modified). So recursion in Python is generally inefficient (compared to languages that do provide tail call optimization). You may also be interested in iterative code that can produce individual permutations given an index number.
Thanks for your answer. Still, it will be great if you can tell me what am i missing in my code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.