Created
August 28, 2014 21:21
-
-
Save nilp0inter/8ebd894a6b54413548b8 to your computer and use it in GitHub Desktop.
Gray codes generator
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
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