How program a particilar algorithm ?
Hans Nowak
wurmy at earthlink.net
Wed Nov 14 13:33:50 EST 2001
Michel Bonnifait wrote:
>
> Hello,
> I think my question is more on programming than specifically on programming
> with Python.
> I want to generate all possible lists with elements from another one. For
> example, from a list like [1,2,3,4] i want to program an algorithm which
> will give this result
> [[1,2],[1,3],[1,4],[1,2,3],[1,2,4],[1,3,4],[1,2,3,4],[2,3],[2,4],[2,3,4],[3,
> 4]]
> It's seems to me it should be a recursive programming answer but i can't
> find it.
> thanks in advance for your help !
This code seems to work:
def perms(lst):
if len(lst) == 1:
return [lst]
# return first element of list, combined with perms
head, tail = lst[0], lst[1:]
ptail = perms(tail)
phead = [[head]+p for p in ptail]
return phead + ptail + perms([head])
lst = [1, 2, 3, 4]
for p in perms(lst):
print p
This question has been asked on the ng before, so you might be able to
find
other (better?) replies by doing a google search or so.
HTH,
--Hans
More information about the Python-list
mailing list