PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

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

 August 10, 2022     binary, decimal, python-3.x, stack     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing