rendered paste body#!/usr/bin/python# Gray code by iterative approach. Public domain. pearfalse.co.ukclass GrayCode: """ Creates a GrayCode proxy object. This object is iterable. __init__(self, n) n = number of bits of gray code required example: from gray2 import GrayCode for gc in iter(GrayCode(4)): print "%d%d%d%d | %d" % ( (1 if gc & 0x8 else 0), (1 if gc & 0x8 else 0), (1 if gc & 0x8 else 0), (1 if gc & 0x8 else 0), gc ) """ def __init__(self, n): #n = ; number of bits required #t = 0 ; total gray code value so far #i = 0 ; iteration variable self.n = n def __iter__(self): self.t = self.i = 0 return self def next(self): if self.i == 2**self.n: raise StopIteration t = 0 # t |= (ith bit xor (i+1)th bit) for pos in range(self.n-1, -1, -1): #print "n=%d, t=%x, i=%d, pos=%d" % (self.n, t, self.i, pos) bitat = (self.i >> (pos)) & 0x1 bitb4 = (self.i >> (pos+1)) & 0x1 #print "%d => %d %d" % (self.i, bitb4, bitat) t <<= 1 t |= (bitat ^ bitb4) self.i += 1 return t if __name__ == '__main__': for gc in iter(GrayCode(4)): print "%d%d%d%d | %d" % ( (1 if gc & 0x8 else 0), (1 if gc & 0x4 else 0), (1 if gc & 0x2 else 0), (1 if gc & 0x1 else 0), gc )