Skip to content

Instantly share code, notes, and snippets.

@nilp0inter
Created August 28, 2014 21:21
Show Gist options
  • Save nilp0inter/8ebd894a6b54413548b8 to your computer and use it in GitHub Desktop.
Save nilp0inter/8ebd894a6b54413548b8 to your computer and use it in GitHub Desktop.
Gray codes generator
class Gray:
def __init__(self, length):
self.length = length
def _right(self, n):
if n == 1:
yield (0,)
yield (1,)
else:
for s in Gray(n-1):
yield (0,) + s
for s in reversed(Gray(n-1)):
yield (1,) + s
def _left(self, n):
if n == 1:
yield (1,)
yield (0,)
else:
for s in Gray(n-1):
yield (1,) + s
for s in reversed(Gray(n-1)):
yield (0,) + s
def __iter__(self):
return self._right(self.length)
def __reversed__(self):
return self._left(self.length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment