Advertisement
mate2code

OEIS A280319 (Steinhaus–Johnson–Trotter algorithm)

Dec 31st, 2016
984
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. # https://oeis.org/A280319
  2. # listing the permutations generated by Steinhaus–Johnson–Trotter algorithm as their reverse colexicographic index numbers
  3. # s_permutations comes from https://rosettacode.org/wiki/Permutations_by_swapping#Python:_recursive
  4.  
  5. from itertools import permutations
  6. from bidict import bidict
  7. from math import factorial
  8.  
  9.  
  10. m = 7
  11.  
  12.  
  13. sjt_numbers = []
  14.  
  15. for n in range(1, m+1):
  16.  
  17.     # generate n-element permutations in reverse colexicographic order
  18.     perms_iter = permutations(list(range(n)))
  19.     perms_revcolex_bidict = bidict()
  20.     for i, perm in enumerate(perms_iter):
  21.         perms_revcolex_bidict[factorial(n)-1-i] = tuple(perm[::-1])  # create reverse colexicographic order
  22.  
  23.     # generate n-element permutations in Steinhaus–Johnson–Trotter order
  24.     def s_permutations(seq):
  25.         def s_perm(seq):
  26.             if not seq:
  27.                 return [[]]
  28.             else:
  29.                 new_items = []
  30.                 for i, item in enumerate(s_perm(seq[:-1])):
  31.                     if i % 2:
  32.                         # step up
  33.                         new_items += [item[:i] + seq[-1:] + item[i:]
  34.                                       for i in range(len(item) + 1)]
  35.                     else:
  36.                         # step down
  37.                         new_items += [item[:i] + seq[-1:] + item[i:]
  38.                                       for i in range(len(item), -1, -1)]
  39.                 return new_items
  40.  
  41.         return [tuple(item) for item in s_perm(seq)]
  42.  
  43.     perms_sjt = s_permutations(list(range(n)))
  44.  
  45.     # assign rev colex index numbers to permutations
  46.     for i in range(factorial(n)):
  47.         perm = perms_sjt[i]
  48.         sjt_number = perms_revcolex_bidict.inv[perm]
  49.         sjt_numbers.append(sjt_number)
  50.  
  51.  
  52. print(sjt_numbers)
  53.  
  54.  
  55. b_file_text = ''
  56.  
  57. for i, e in enumerate(sjt_numbers):
  58.     b_file_text += '%s %s\n' % (i, e)
  59.  
  60. b_file = open('b_file', 'w')
  61. b_file.write(b_file_text)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement