bol_in 2021-12-08 11:44 采纳率: 64.6%
浏览 67
已结题

資料結構問題請求協助

請問這題誰有其他意見
爬了很多資料很多網站
都還是沒有找到類似的
請求各位幫忙處理


(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.

  • 写回答

2条回答 默认 最新

  • 关注
    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()
    

    img

    img

    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 12月16日
  • 修改了问题 12月8日
  • 创建了问题 12月8日

悬赏问题

  • ¥15 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络