Advertisement
mate2code

OEIS A280318 (Heap's algorithm)

Dec 31st, 2016
1,156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. # https://oeis.org/A280318
  2. # listing the permutations generated by Heap's algorithm as their reverse colexicographic index numbers
  3. # _heap_perm_ comes from http://stackoverflow.com/questions/29042819/heaps-algorithm-permutation-generator
  4.  
  5. from itertools import permutations
  6. from bidict import bidict
  7. from math import factorial
  8.  
  9.  
  10. n = 7
  11.  
  12. # generate n-element permutations in reverse colexicographic order
  13. perms_iter = permutations(list(range(n)))
  14. perms_revcolex_bidict = bidict()
  15. for i, perm in enumerate(perms_iter):
  16.     perms_revcolex_bidict[factorial(n)-1-i] = tuple(perm[::-1])  # create reverse colexicographic order
  17.  
  18. # generate n-element permutations in Heap order
  19. def _heap_perm_(n, A):
  20.     if n == 1: yield A
  21.     else:
  22.         for i in range(n-1):
  23.             for hp in _heap_perm_(n-1, A): yield hp
  24.             j = 0 if (n % 2) == 1 else i
  25.             A[j],A[n-1] = A[n-1],A[j]
  26.         for hp in _heap_perm_(n-1, A): yield hp
  27.  
  28. heap_generator = _heap_perm_(n, list(range(n)))
  29. perms_heap = {}
  30. for i, perm in enumerate(heap_generator):
  31.     perms_heap[i] = tuple(perm)
  32.  
  33. # assign rev colex index numbers to permutations
  34. heap_numbers = []
  35. for i in range(factorial(n)):
  36.     perm = perms_heap[i]
  37.     heap_number = perms_revcolex_bidict.inv[perm]
  38.     heap_numbers.append(heap_number)
  39.  
  40.  
  41. print(heap_numbers)
  42.  
  43. b_file_text = ''
  44.  
  45. for i, e in enumerate(heap_numbers):
  46.     b_file_text += '%s %s\n' % (i, e)
  47.  
  48. b_file = open('b_file', 'w')
  49. b_file.write(b_file_text)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement