-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraycode.py
More file actions
61 lines (40 loc) · 1.06 KB
/
graycode.py
File metadata and controls
61 lines (40 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from copy import copy
#
# - https://en.wikipedia.org/wiki/Gray_code
#
def reflected(n):
if n == 0:
return [0]
if n == 1:
return [0, 1]
prv = reflected(n - 1)
tmp = copy(prv)
return prv + [(1 << (n - 1)) | code for code in tmp[::-1]]
def shifted(n):
#
# - took me a while to spot the fact each bit is flipped iif its left-side neighbour is on
#
return [i ^ (i >> 1) for i in range(2 ** n)]
def n_ary(base, token):
digits = []
while token:
digits.append(token % base)
token /= base
if not digits:
digits = [0]
gray = []
shift = 0
for digit in digits[::-1]:
tmp = (digit + shift) % base
shift += base - tmp
gray.append(tmp)
return gray
def n_ary_words(n):
return [''.join([chr(65 + digit) for digit in n_ary(26, i)]) for i in range(2 ** n)]
if __name__ == '__main__':
print reflected(5)
print shifted(5)
#
# - fun: generate tokens in base-26 (A-Z) using n-ary gray codes
#
print(n_ary_words(10))