# Creating the table of 4-element permutations and all the inversion related vectors in # https://en.wikiversity.org/wiki/Inversion_(discrete_mathematics)#Example:_All_permutations_of_four_elements from itertools import permutations def based_0_or_1(perm): # returns 0 if the permutation is 0-based and 1 if it is 1-based length = len(perm) if sorted(perm) == list(range(length)): return 0 elif sorted(perm) == list(range(1, length+1)): return 1 else: print('Input is no 0-based or 1-based permutation.') def zeroify(perm): # returns a 0-based permutation base = based_0_or_1(perm) if base == 0: return perm if base == 1: return [i-1 for i in perm] def l_inv_count(perm): length = len(perm) result = [0] * length for i in range(length): count = 0 for k in range(i): if perm[k] > perm[i]: count += 1 result[i] = count return result def r_inv_count(perm): length = len(perm) result = [0] * length for i in range(length): count = 0 for k in range(i+1, length): if perm[k] < perm[i]: count += 1 result[i] = count return result def inv_vect(perm_in): perm = zeroify(perm_in) length = len(perm) result = [0] * length for i in range(length): count = 0 for k in range(i): if perm[k] > perm[i]: count += 1 result[perm[i]] = count return result def l2s(l): # turns [1, 2, 3] to '123' s = '' for e in l: s += str(e) return s inv = [0, 1, 2, 4, 3, 5, 6, 7, 12, 18, 13, 19, 8, 10, 14, 20, 16, 22, 9, 11, 15, 21, 17, 23] perms_iter = permutations([1, 2, 3, 4]) perms_dict = {} for i, perm in enumerate(perms_iter): perms_dict[23-i] = perm[::-1] # create reverse colexicographic order def c(abbrs): # turns c('rs') to ' ||style="color:red;font-size:50%;"| ' abbr_to_code = { 'b': 'font-weight:bold;', 'x': 'font-size:40%;', 's': 'font-size:50%;', 'l': 'font-size:110%;', 't': 'border-left:3px solid darkgray;', 'r': 'color:red;' } res = ' ||style="' for abbr in abbrs: res += abbr_to_code[abbr] res += '"| ' return res table = '' for i in range(24): perm = perms_dict[i] p = l2s(perm) l = l2s(l_inv_count(perm)[1:]) r = l2s(r_inv_count(perm)[:-1]) v = l2s(inv_vect(perm)[:-1]) invnum = str(sum(inv_vect(perm))) if i in [1, 2, 5, 6, 14, 21]: numcolor = '33eb2a' # green elif i in [9, 10, 13, 17, 18, 22]: numcolor = 'ffbb00' # orange else: numcolor = 'ffffff' # white if i in [0, 7, 16, 23]: numweight = 'font-weight:bold;' else: numweight = '' start = '\n|- style="height:38px"\n|style="font-size:110%;background-color:#' + numcolor + ';' + numweight \ + 'letter-spacing:0;"| ' + str(i) \ + ' || [[File:4-el perm matrix ' + str(i).zfill(2) + '.svg|30px]]' z = '0' row = start \ + c('b') + p + c('bx') + p[::-1] \ + c('t') + '[[File:4-el perm invset ' + str(inv[i]).zfill(2) + '.svg|55px]]' \ + c('tr') + v+z + c('rs') + z+v[::-1] \ + c('trs') + l[::-1]+z + c('r') + z+l \ + c('t') + '[[File:4-el perm invset ' + str(i).zfill(2) + '.svg|55px]]' \ + c('tr') + r+z + c('rs') + z+r[::-1] \ + c('trl') + invnum table += row print(table)