list question... unique values in all possible unique spots

Mensanator mensanator at aol.com
Sat Aug 9 17:07:26 CEST 2008


On Aug 9, 8:05�am, ToshiBoy <Toshi... at gmail.com> wrote:
> I'm wondering how to do this the most elegant way: I found this quiz
> in some magazine. I've already solved it on paper, but want to write a
> python program to solve it. It comes down to being able to represent
> range(1,27) through a number of formulas. How do I write a loop that
> will loop through this list, so that: 1. every number only occurs
> once, and 2. I get every possibility of order within the list? I guess
> it'd be somewhat similar to Sudoku, where you have the numbers from
> 1-9 in any possible order. Here it's 1-26.

Python 2.6 has a permutation function:

IDLE 2.6b1
>>> import itertools
>>> for i in itertools.permutations(range(4)): print i

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

Bur bear in mind that permutations of size n are n!.
So the permutaions of range(1,27) is 26! which is

>>> print gmpy.fac(26)
403291461126605635584000000

That's 403 octillion.

Are you sure you want to do this?



More information about the Python-list mailing list