Permutations using a recursive generator

Thomas Jollans tjol at tjol.eu
Tue Sep 18 11:21:10 EDT 2018


On 2018-09-18 17:05, ast wrote:
> Le 18/09/2018 à 17:01, ast a écrit :
>> Hello
>> 
>> I found a smart and very concise code to
>> generate all permutations of a list.
>> I put it here if someone is interested to
>> figure out how it works

When you say "found a [...] code" I hope you mean "wrote a function"
rather than "discovered a bit of code and decided to share it without
attribution or permission".

>> 
>> 
>> def permut(li, prefix=[]):
>> 
>>     if len(li)==1:
>>         yield prefix + li
>>     else:
>>         for elt in li:
>>             li2 = li.copy()
>>             li2.remove(elt)
>>             yield from S(li2, prefix+[elt]) >
> error: permut instead of S
> 
>>              yield from permut(li2, prefix+[elt])

Nice. If you want to see more implementations of the same thing, have a
look in the standard library docs ;-)

https://docs.python.org/3/library/itertools.html#itertools.permutations







More information about the Python-list mailing list