Skip to content

Instantly share code, notes, and snippets.

@st0le
Last active December 18, 2015 08:59
Show Gist options
  • Save st0le/5758462 to your computer and use it in GitHub Desktop.
Save st0le/5758462 to your computer and use it in GitHub Desktop.
Gray Codes
"""
For a +ve integer n, print numbers from 0 to 2^n-1 such that numbers next to each other differ in exactly 1 bit.
"""
n = 3
gray = lambda x : (x >> 1) ^ x
pad_left = lambda s,l: ''.join(['0']*(l-len(s))) + s
for i in xrange(1 << n):
print i,pad_left(bin(gray(i))[2:],n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment