Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get all permutations of numbers

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

like image 978
Sam Machin Avatar asked Jan 12 '10 22:01

Sam Machin


People also ask

How do you find all the permutations of a number in Python?

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.

How do you generate all permutations of an array?

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.


1 Answers

>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}
like image 145
SilentGhost Avatar answered Sep 22 '22 05:09

SilentGhost