請問這題誰有其他意見
爬了很多資料很多網站
都還是沒有找到類似的
請求各位幫忙處理
(Programming)
A Gray code is an encoding of numbers so that two contiguous numbers have a single digit differing by 1. The term Gray code is often used to refer to a ”reflected” code, or more specifically still, the binary reflected Gray code. For example, one-bit Gray code is G1 = (0, 1) and two-bit Gray code is G2 = (00, 01, 11, 10). Three-bit Gray code is as follows:
Dec Gray
0 000
1 001
2 011
3 010
4 110
5 111
6 101
7 100
This exercise asks you to list the n-bit Gray code using a stack. Your Python program should read a value n (the number of bits for the Gray code) and use a stack to help you to generate the n-bit Gray codes as well as list them in order.
class Stack():
def __init__(self, size):
self.size = size
self.stack = []
self.top = -1
def push(self, x): # 入栈之前检查栈是否已满
if self.isfull():
pass
# 不做操作
else:
self.stack.append(x)
self.top = self.top + 1
def pop(self): # 出栈之前检查栈是否为空
if self.isempty():
print("stack is empty")
else:
self.top = self.top - 1
self.stack.pop()
def isfull(self): # 是否满栈
return self.top + 1 == self.size
def isempty(self): # 判断是否为空
return self.top == -1
def showStack(self): # 显示栈内数据
for i in range(len(self.stack)):
print(i, self.stack[i])
n = int(input())
greelist = []
# 设置堆栈大小,为数据大小
Stack = Stack(2**n)
for i in range(0, 2 ** n):
gree = i ^ (i >> 1)
str1 = str(bin(gree))[2:]
Stack.push(str1.zfill(n))
# 查看堆栈内数据
Stack.showStack()
堆栈方式
class stack():
def __init__(self):
self.l=[]
def In(self,v):
self.l.append(v)
def out(self):
tmp=self.l[-1]
del(self.l[-1])
return tmp
def gray(n):
s=stack()
t=2**n-1
for i in range(t+1):
tt=t>>1
g=t^tt
k=2**(n-1)
tmp=''
for j in range(n):
if g&k:
tmp+='1'
else:
tmp+='0'
k>>=1
s.In(tmp)
t-=1
for i in range(2**n):
print(s.out())
gray(4)