[Tutor] permutations?
Steven D'Aprano
steve at pearwood.info
Thu Dec 2 00:05:47 CET 2010
Alex Hall wrote:
> Hi all,
> I am wondering if there is a python package that will find
> permutations?
What version of Python are you using?
Starting from Python 2.6, the itertools module contains combinations,
permutations and Cartesian product:
>>> list(itertools.combinations([1,2,3], 1))
[(1,), (2,), (3,)]
>>> list(itertools.combinations([1,2,3], 2))
[(1, 2), (1, 3), (2, 3)]
>>> list(itertools.combinations([1,2,3], 3))
[(1, 2, 3)]
>>> list(itertools.permutations([1,2,3], 1))
[(1,), (2,), (3,)]
>>> list(itertools.permutations([1,2,3], 2))
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
>>> list(itertools.permutations([1,2,3], 3))
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
>>> list(itertools.product([1,2,3], 'ab'))
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
For example, if I have (1, 2, 3), the possibilities I
> want are:
> 12
> 13
> 23
> 123
> 132
> 231
>
> Order does not matter;
According to your example, it certainly does -- you have 123 and 132 and
231 listed as three distinct possibilities.
--
Steven
More information about the Tutor
mailing list