First of all, the above code you have pasted has lots of indentation issues, next time you should try to fix those indentation issues and running your program again, before posting it here.
Secondly, your logic is also wrong, you should not be checking -
while newNum == 1:
at start itself, you are setting newNum = decNum , unless you enter 1 , your program would not enter that while loop. The condition you need is -
while decNum != 0:
Secondly, the second while loop, should not be inside the first while loop, it should be outside, so that you print out the stack once all the computation is complete. Also , you don't even need the first newNum = decNum , before the loop starts.
I fixed all your indentation issues, and logical issues, the code is -
import sys
class Stack ():
def __init__(self):
self.items=[]
def push (self,item):
self.items.append(item)
def pop (self):
return self.items.pop()
def size(self):
return len(self.items)
s1= Stack()
decNum= int(raw_input("Enter the decimal num : "))
while decNum!=0:
newNum= decNum%2
decNum = decNum//2
s1.push(newNum)
while s1.size() != 0:
a=s1.pop()
sys.stdout.write(str(a))
sys.stdout.flush()
Answer from Anand S Kumar on Stack Overflowpython - Decimal to binary algorithm - Code Review Stack Exchange
python - Decimal to binary using stack but not sure how the input should be a stack itself - Stack Overflow
How Convert decimal to binary using stack?
Python: Decimal to Binary - Stack Overflow
This may also work
def DecimalToBinary(number):
#This function uses recursion to convert & print decimal to binary number
if number > 1:
convertToBinary(number//2)
print(number % 2,end = '')
# decimal number
decimal = 34
convertToBinary(decimal)
#..........................................
#it will show output as 110100
You faced error because you adding numbers and not iterables but want to get bits sequences...,so you have to convert values you are adding to tuples or strings (or lists), see code below:
def decimalToBinary(value):
if value < 0: #Base case if number is a negative
return 'Not positive'
elif value == 0: #Base case if number is zero
return (0,)
else:
return decimalToBinary(value//2) + (value%2,)
print decimalToBinary(12)
I've replaced (value%2) to (value%2,) to create tuple(, matter, for python it's mean creating a tuple, braces aren't do it... ) and return 0 to return (0,). However you can convert it to string too. For that replace (value%2) to str(value%2 and 0 to str(0).
Note that you can use built-int bin function ti get binary decimal:
print bin(12) # 'ob1100'
Good luck in your practice !
You can probably use the builtin bin function:
bin(8) #'0b1000'
to get the list:
[int(x) for x in bin(8)[2:]]
Although it seems like there's probably a better way...
Try this:
>>> list('{0:0b}'.format(8))
['1', '0', '0', '0']
Edit -- Ooops, you wanted integers:
>>> [int(x) for x in list('{0:0b}'.format(8))]
[1, 0, 0, 0]
Another edit --
mgilson's version is a little bit faster:
$ python -m timeit "[int(x) for x in list('{0:0b}'.format(8))]"
100000 loops, best of 3: 5.37 usec per loop
$ python -m timeit "[int(x) for x in bin(8)[2:]]"
100000 loops, best of 3: 4.26 usec per loop
all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)
>>> bin(10)
'0b1010'
>>> 0b1010
10
Without the 0b in front:
"{0:b}".format(int_value)
Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:
f"{int_value:b}"
Would someone be willing to help me (total beginner) understand how this converts decimal values to binary? Maybe just by explaining what happens line by line?
def dec2bin(n):
if n > 1:
dec2bin(n//2)
print(n % 2, end="")It's just not intuitive at all for me :/
Any help would be greatly appreciated!
