I'm trying to display all possible permutations of a list of numbers, for example if I have 334 I want to get:
3 3 4
3 4 3
4 3 3
I need to be able to do this for any set of digits up to about 12 digits long.
I'm sure its probably fairly simple using something like itertools.combinations but I can't quite get the syntax right.
TIA Sam
To find all possible permutations of a given string, you can use the itertools module which has a useful method called permutations(iterable[, r]). This method return successive r length permutations of elements in the iterable as tuples.
You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element.
>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With