From fb13b3ce62760dc7c711bb697b90e39d6458ed46 Mon Sep 17 00:00:00 2001 From: Correl Roush Date: Thu, 29 Apr 2010 03:25:47 +0000 Subject: [PATCH] Problem 024 git-svn-id: file:///srv/svn/euler@56 e5f4c3ec-3c0c-11df-b522-21efaa4426b5 --- e024.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 e024.py diff --git a/e024.py b/e024.py new file mode 100644 index 0000000..3960f9d --- /dev/null +++ b/e024.py @@ -0,0 +1,29 @@ +import math + +def lexicographic_permutation(list, position): + items = len(list) + list = sorted(list) + p = [] + position = position - 1 + while len(p) < items: + index = 0 + # Find the next index to pop + l = len(list) - 1 + f = math.factorial(l) if l else 0 + while position and position >= f: + position = position - f + index = index + 1 + + p.append(list.pop(index)) + return p + +if __name__ == '__main__': + print 'Testing permutations of 0..2:' + list = [str(i) for i in [0, 1, 2]] + for i in range(1, math.factorial(len(list)) + 1): + p = lexicographic_permutation(list, i) + print '\tPermutation', i, ''.join(p) + + list = [str(i) for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] + p = lexicographic_permutation(list, 1000000) + print '1 millionth lexicographic permutation of 0..9:', ''.join(p)