Last active
July 16, 2021 05:27
-
-
Save belisarius222/47ffa1d3100c6757f9c8 to your computer and use it in GitHub Desktop.
Gray codes in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def gray(n): | |
if n == 1: | |
return ["0", "1"] | |
originals = gray(n - 1) | |
prefixedOriginals = ["0" + d for d in originals] | |
reflected = list(reversed(originals)) | |
prefixedReflected = ["1" + d for d in reflected] | |
return prefixedOriginals + prefixedReflected | |
balancedGray8 = """ | |
00 01 03 02 06 0E 0A 0B 09 0D 0F 07 05 04 0C 08 | |
18 1C 14 15 17 1F 3F 37 35 34 3C 38 28 2C 24 25 | |
27 2F 2D 29 39 3D 1D 19 1B 3B 2B 2A 3A 1A 1E 16 | |
36 3E 2E 26 22 32 12 13 33 23 21 31 11 10 30 20 | |
60 70 50 51 71 61 63 73 53 52 72 62 66 6E 7E 76 | |
56 5E 5A 7A 6A 6B EB EA FA DA DE D6 F6 FE EE E6 | |
E2 F2 D2 D3 F3 E3 E1 F1 D1 D0 F0 E0 A0 B0 90 91 | |
B1 A1 A3 B3 93 92 B2 A2 A6 AE BE B6 96 9E 9A BA | |
AA AB BB 9B 99 9D DD D9 DB FB 7B 5B 59 5D 7D 79 | |
F9 FD BD B9 A9 E9 69 6D 6F 67 65 64 E4 E5 E7 EF | |
ED AD AF A7 A5 A4 AC EC 6C 68 E8 A8 B8 F8 78 7C | |
FC BC B4 B5 B7 F7 F5 F4 74 75 77 7F FF BF 9F DF | |
5F 57 55 54 D4 D5 D7 97 95 94 9C DC 5C 58 D8 98 | |
88 C8 48 4C CC 8C 84 C4 44 45 C5 85 87 C7 47 4F | |
CF 8F 8D CD 4D 49 C9 89 8B CB 4B 4A CA 8A 8E CE | |
4E 46 C6 86 82 C2 42 43 C3 83 81 C1 41 40 C0 80 | |
""".split() | |
# Represent 0's with spaces, and 1's with white blocks. | |
o = " " | |
l = "\u2588" | |
def printGrayCode(grayCode): | |
for i in range(8): | |
for b in grayCode: | |
print(l if b[i] == '1' else o, end='') | |
print() | |
# Get a string like '00011010' from an integer. | |
toBin = lambda x: "0" * (8 - len(bin(x)) + 2) + bin(x)[2:] | |
g8 = [toBin(g) for g in balancedGray8] | |
printGrayCode(g8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For a more general balanced Gray code generation method, you might find this useful.