简体   繁体   English

为什么我的 Python 代码无法使用堆栈将数字转换为二进制?

[英]Why is my python code to convert an number to binary using stack not working?

The following is my code to convert a number to binary using stacks written in Python3.以下是我使用 Python3 编写的堆栈将数字转换为二进制的代码。 Whenever I run it, None is produced as the output.每当我运行它时,都会生成None作为输出。 What might be causing this?这可能是什么原因造成的? Thanks in advance.提前致谢。

class Stack():
    def __init__(self):
        self.stack = []
        self.top = -1

def push(self, val):
    self.stack.append(val)
    self.top += 1

def pop(self):
    if self.top == -1:
        print('Underflow')
    else:
        del self.stack[self.top]
        self.top -= 1

def empty(self):
    return self.stack == []

def peek(self):
    return self.top

def display(self):
    return self.stack

def binary(n):
    b = Stack()
    while n > 0:
        r = n%2
        b.push(r)
        n = n//2

    bn = ''
    while not b.empty():
        bn += str(b.pop())

    return bn

print(binary(242))

This line just pops the elements from the stack and does not return anything.It returns None.此行只是从堆栈中弹出元素,不返回任何内容。它返回 None。

bn += str(b.pop()) 

You must store the top element in a variable and then pop the stack after it.您必须将顶部元素存储在一个变量中,然后在它之后弹出堆栈。

Try this below in your binary function :在您的二元函数中尝试以下操作:

def binary(n):
    b = Stack()
    while n > 0:
        r = n % 2
        b.push(r)
        n = n//2
    print(b.stack)
    bn = ''
    while not b.empty():
        bn += str(b.stack[-1])
        b.pop()
    return bn

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM