interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / permutations-by-swapping / oracle.py

20 lines · 847 bytes Raw Blame History
1# Independent reference for "Permutations by swapping" (Python 3, standard library only).
2# expected.txt is this program's stdout; omc never produced it.
3# the same order built recursively: the element n sweeps right to left through the first order of
4# n-1 elements, then left to right through the next, and so on; the sign is the inversion parity
5def sjt(n):
6 if n == 1:
7 return [[1]]
8 out = []
9 for i, p in enumerate(sjt(n - 1)):
10 spots = range(n - 1, -1, -1) if i % 2 == 0 else range(n)
11 out += [p[:k] + [n] + p[k:] for k in spots]
12 return out
13def sign(p):
14 inv = sum(1 for i in range(len(p)) for j in range(i + 1, len(p)) if p[i] > p[j])
15 return -1 if inv % 2 else 1
16for n in (3, 4):
17 if n == 4:
18 print()
19 for p in sjt(n):
20 print(f"Perm: [{', '.join(map(str, p))}] Sign: {sign(p)}")