Advertisement
makispaiktis

Project Euler 24 - Lexicographic Permutations

May 12th, 2020 (edited)
1,397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. '''
  2. A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
  3. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
  4. 012   021   102   120   201   210
  5. What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
  6. '''
  7. def factorial(n):
  8.     if n < 0 or n != int(n):
  9.         return None
  10.     if n == 0:
  11.         return 1
  12.     else:
  13.         return n * factorial(n-1)
  14.  
  15. from itertools import permutations
  16. N = 10
  17. targetIndex = 1000000
  18. perm = permutations(range(0, N))
  19. # Check condition
  20. if targetIndex > factorial(N):
  21.     print("There is not such a permutation.")
  22.  
  23. counter = 0
  24. for p in perm:
  25.     # print(p)
  26.     counter += 1
  27.     if counter == targetIndex:
  28.         print("The lexicographic permutation of a list from 0 to " + str(N-1) + " in index " + str(targetIndex) + " is: " + str(p))
  29.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement