Skip to content

Instantly share code, notes, and snippets.

@nilp0inter
Created August 28, 2014 21:28
Show Gist options
  • Save nilp0inter/b310b28f1e49fbe3ea24 to your computer and use it in GitHub Desktop.
Save nilp0inter/b310b28f1e49fbe3ea24 to your computer and use it in GitHub Desktop.
class Gray:
def __init__(self, length):
self.length = length
def _gen(self, start, end, n):
if n == 1:
yield (start, )
yield (end, )
else:
for s in Gray(n-1):
yield (start,) + s
for s in reversed(Gray(n-1)):
yield (end,) + s
def __iter__(self):
return self._gen(0, 1, self.length)
def __reversed__(self):
return self._gen(1, 0, self.length)
if __name__ == '__main__':
print(list(Gray(2)))
print(list(Gray(3)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment