Re: Permutations using a recursive generator

2018-09-18 Thread Thomas Jollans
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




-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Permutations using a recursive generator

2018-09-18 Thread ast

Le 18/09/2018 à 17:01, ast a écrit :

error: permut instead of S


     yield from permut(li2, prefix+[elt])

--
https://mail.python.org/mailman/listinfo/python-list


Permutations using a recursive generator

2018-09-18 Thread ast

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


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])


exemple of usage

>>> list(permut(['a', 'b', 'c']))
[['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], 
['c', 'a', 'b'], ['c', 'b', 'a']]


>>> list(permut([0,1,2,3]))
[[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], 
[0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], 
[1, 3, 0, 2], [1, 3, 2, 0], [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3], 
[2, 1, 3, 0], [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 0, 2, 1], 
[3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]]

--
https://mail.python.org/mailman/listinfo/python-list