Issue
The following is my code to convert a number to binary using stacks written in Python3.
Whenever I run it, None
is produced as the output. 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))
Solution
This line just pops the elements from the stack and does not return anything.It returns 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
Answered By - Abhishek Kulkarni Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.