osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Permutations using a recursive generator


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