So far I have a function that creates gray code then I need to make a function that will return the gray code "plus one", basically the next in sequence. so if D = (0,0,1,1) I need to return (0,0,1,0)
I have
def gray(x):
if x:
return ['0' + x[0]] + gray(x[1:]) + ['1' + x[0]]
else:
return []
def graycode(n):
if n:
return gray(graycode(n-1))
else:
return ['']
then lastly,
def GrayFinal(D):
z = ''.join(map(str,D))
str(z)
if z in graycode(len(D)):
return graycode(len(D))[z+1]
else:
return ['']
I can't figure out how to return the Zth+1 entry
If I interpreted your question correctly, the heart of your question really has nothing to do with Gray codes, but rather with the more general question, " Given an element I wish to find in a Python list, how do I retrieve the next element after that? "
Unfortunately I can only come up with a rather brain-dead solution right now which is
def next_elem(elem, input_list):
index = input_list.index(elem)
return input_list[index + 1]
Note that this has absolutely no support whatsoever for error checking, which I assume in your case would be done in the body of the code. Throwing that into your code would result in the following:
def GrayFinal(D):
z = ''.join(map(str,D))
try:
return next_elem(z, graycode(len(D)))
except ValueError:
# Doesn't look like z was ever in the Gray code generated
return ['']
except IndexError:
# The next element is beyond the last element of the array!
return next_elem('0' + z, graycode(len(D) + 1))
Here something I heard about:
>>> bin2gray = lambda x: (x >> 1) ^ x # create graycode
>>> for i in range(10):
print(bin(bin2gray(i))[2:].zfill(4))
0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
>>> def gray2bin(g):
bits = list(map(int, bin(g)[2:]))
n = [0]
for bit in bits:
if not n[-1]:
n.append(bit)
else:
n.append(1 - bit)
return sum([n[i] << (-1 - i) for i in range(-len(n), 0)])
>>> def inc(g):
return bin2gray(gray2bin(g) + 1)
You will need to adapt the inc function if you want it to work with strings instead of ints.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.