Decimals to binary in Python - python

I'm trying to use a function (dec2bin()) to convert decimal numbers to binary. I see the input number being printed as binary but in the wrong order. What do I need to change? Or do I need to start over?
Here is the code with the function at first then the program:
def dec2bin(value):
if value > 1:
dec2bin(value//2)
print (value%2, end = '')
invalue_ok = False
invalue = 0
while invalue_ok is False:
invalue = int(input("Give a value: "))
if invalue > 65535:
print ("Wrong. Number too big. Try again.")
elif invalue < 0:
print ("Wrong. Can only handle positive numbers.")
if invalue < 256:
print ("Number", invalue, "fits in one byte and in binary is ", dec2bin(invalue))
else:
print ("Number", invalue, "fits in 16 bytes and in binary is", dec2bin(invalue))`
The output looks like this:
Give a value: 234
1101010Number 234 fits in one byte and in binary is None
What can I do to get it right?

it works with
if value>0:
it's in the good order

There are three easier ways to do it:
The format method:
binary = "{0:b}".format(*number*)
The bin method (this also works with negative numbers):
binary = bin(*number*)
Or a function from this thread:
def intToBin(n):
if(n < 0):
return -1
elif(n == 0):
return str(n)
else:
result = ""
while(n != 0):
result += str(n%2)
n //= 2
return result[::-1]
binary = intToBin(*number*)

Related

Convert decimal number to binary

This is all the further i've gotten.
import math
num_to_convert = int(input("Please enter any intger from 1 and 100:"))
while num_to_convert < 1 or num_to_convert > 100:
num_to_convert = int(input("Sorry that's not an integer from 1 to 100, try again:"))
else:
print("I'm lost!")
I found this but I don't understand whats going on. Maybe some explanation of what's going on would help.
def decimalToBinary(n):
if(n > 1):
# divide with integral result
# (discard remainder)
decimalToBinary(n//2)
print(n%2, end=' ')
It seems like you want to convert an integer which is not a decimal to binary from your code i would write
while True:
try:
value1=input("Integer you want to convert to binary: ")
binaryvalue=(bin(int(value1)))
print (binaryvalue[2:])
except:
print("I did not understand that")
pass
Valuetoconvert=int(input("Number to convert: "))
u = format(Valuetoconvert, "08b")
print(u)
Try this then
See Below:
def toBin(n):
if n < 2:
return str(n)
else:
if n % 2 == 0:
return toBin(n//2) + "0"
else:
return toBin(n//2) + "1"
Explanation:
This is my sollution which works similar to yours. I hope you know what recursion is otherwise this is going to be difficult to understand.
Anyway the algorithm is to devide the number repeatedly by 2 until the number is smaller than 2 cause then you have the sollution right away(base case).
When the current number is greater than 2 you check wether it is
divisible by 2. If it is even you append a 0 to your string else append a 1. You can try this out on paper to better understand it.

function that reverses digits, takes into consideration the sign

I've looked on the site to try and figure out how to do this but I'm still stuck.
My function is supposed to reverse digits, so reverse_digits(8765) returns 5678. This is easily done by :
def reverse_digits(num):
return int(str(num)[::-1])
However, my code needs to 1) test if it is a negative and keep it negative (so -8765 returns -5678) and 2) I think I should test to see if num is actually an int.
So far I have
def reverse_digits(num):
num = str(num)[::-1]
if num == '-':
minus = 1
num = num[:-1]
else:
minus = 0
int(num)
if minus == 1:
num = num*-1
else:
num = num
return num
It works for digits without a '-', but returns '' when it has a '-'.
I was originally trying to put the test to see if it is an int at the beginning od the loop like
if (num != int):
print("wrong type")
sys.exit()
else:
(the rest of my above code)
but that wouldn't work for me. Should I put all the code in a while loop so I can use continue/break?
Thanks!
Just don't put the - into the reversed string:
def reverse_digits(num):
return (-1 if num<0 else 1) * int(str(abs(num))[::-1])
Try to use the isdigit() string method.
def reverse_digit(num):
num_str = str(num)[::-1].strip('-')
if not num_str.isdigit():
<do what u want>
if num < 0:
return -int(num_str)
else:
return int(num_str)

Python: Decimal to Binary

I'm trying to get the function to work, it is suppose to convert Decimal to Binary but all it gives me different numbers instead. Like if I enter 12, it would give me 2. I'm not sure where in the code my issue is located. Any help would be great, thank you!
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)
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 !
What about bin?
>>> bin(12)
'0b1100'
>>> bin(0)
'0b0'
>>> bin(-1)
'-0b1'
You should use bin(), a built-in python function
https://docs.python.org/3.1/library/functions.html#bin
Your problem is that you're adding up the digits of your result in decimal. So if your result was going to be 01100, your function is outputting 0+1+1+0+0 which is equal to 2. If you want your digits to stack up, then convert your results to string and concatenate:
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 str(decimalToBinary(value//2)) + str((value%2))
print decimalToBinary(12) # prints '01100
I am assuming you're doing this for practice, and that you're aware of python's built in function bin() that already does that for you.
As an exercice, two way :
with strings:
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 ''
else:
return decimalToBinary(value//2) + str(value%2)
with ints:
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 10*decimalToBinary(value//2) + value%2
In this case, you obtain a decimal whose digits are only 1 or 0.
I would take another aproach:
def decimalToBinary(number):
if number<0:
return 'Not positive'
i = 0
result = ''
while number>>i:
result = ('1' if number>>i&1 else '0') + result
i += 1
return result

Binary and Denary converter in python

I am quite new to python and i want to create a binary to decimal converter and a decimal to binary converter.
However the binary number the user wants to convert can only be eight digits long and has to be a valid binary number, and the deciamal number the user wants to convert can only be positive and up to 255.
I came up with this code and I'm stuck with the 'However' part.
import time
def program():
a = input ("Would you like to convert Denary To Binary (D) or Binary To Denary (B)? ")
if a == ("D") :
def denary():
print("The denary number you want to convert, can only be a positive number up to 255")
time.sleep(2)
e= int(input("What number would you like to convert into Binary? "))
if e < 255 or e==255 or e >= 0:
print(bin(e)[2:].zfill(8))
again=int(input("Would you like to go again YES[1] NO[2]"))
if again==(1):
program()
else:
print ("Thank you for using the program")
else:
denary()
denary()
elif a == ("B"):
def binary():
print("The binary number you want to convert, can only be eight digits long and can only be a valid binary, number consiting of 0's and 1's")
time.sleep(2)
c = int(input("What Binary number would you like to convert into Denary? "))
if len(c) >8 and c== '0' or '1':
convert= lambda b: str(int(b, 2))
print(c + " is " + convert(c) + " in Denary")
again=int(input("Would you like to convert a number again YES[1] NO[2]"))
if again==(1):
program()
else:
print ("Thank you for using the program")
else:
binary()
binary()
else:
program()
program()
if e < 255 or e==255 or e >= 0:
You don't want or here. This branch will be taken if at least one of the conditions is true. 1000 satisfies e >= 0, so 1000 will pass the check. -1000 satisfies e < 255, so -1000 will pass the check. In fact, every number will pass through here. You want
if e >= 0 and e <= 255:
or, using Python's comparison chaining,
if 0 <= e <= 255:
if len(c) >8 and c== '0' or '1':
This makes no sense.
First, c is already an int; you're trying to manipulate it as a string.
Second, the length test shouldn't be checking that the length is greater than 8. It should be == 8 if you need an exact match or <= 8 if any length up to 8 works.
Third, the part of this after the and makes no sense. x == y or z doesn't test whether x is equal to one of y or z. It's interpreted as (x == y) or z, which is usually nonsense.
Finally, even if c== '0' or '1' tested whether c were one of '0' or '1', that still wouldn't be a meaningful thing to do. If you want to test whether all the characters in c are '0' or '1', you can use all with a generator expression:
all(char in ('0', '1') for char in c)
Addressing all those issues, we have the following:
c = input("What Binary number would you like to convert into Denary? ")
if len(c) == 8 and all(char in ('0', '1') for char in c):
Here are the basic conversion functions that should get you going:
def dec2bin(N):
if not N:
return ''
else:
return dec2bin(N//2) + str(N%2)
def bin2dec(b):
answer = 0
for char in b:
answer *= 2
answer += int(char)
return answer
def program():
answer = input("Do you want to convert decimal to binary (D) or ...: ")
if answer == "D":
N = int(input("Enter your number: "))
print("The binary of %s is %s" %(N, dec2bin(N)))
# remainder of the UI logic goes here
leverage your builtins!
dec to bin:
def to_bin(n): #assuming n is a str
"""If the str n represents a number in the range [0, 256), return a
binary string representation of that number, otherwise raise a ValueError
"""
if 0 <= int(n) < 256: # if n is in the valid range
return bin(int(n))[2:] #builtin :p
else:
raise ValueError('number must be in range [0, 256)')
bin to dec
def to_dec(n):
"""If the str n is at most 8 characters long and consists only of '0' and
'1' characters, return the decimal string representation of it, otherwise
raise a ValueError
"""
if len(n) <= 8 all(c in ('0', '1') for c in n):
return str(int(n, 2))
else:
raise ValueError('binary number must be <= 8 digits and consist of 0 and 1')

Using Python, reverse an integer, and tell if palindrome

Using Python, reverse an integer and determine if it is a palindrome. Here is my definition of reverse and palindrome. Do I have a correct logic?
def reverse(num):
s=len(num)
newnum=[None]*length
for i in num:
s=s-1
newnum[s]=i
return newnum
def palindrome(num):
a=str(num)
l=len(z)/2
if a[:1]==a[-1:][::-1]:
b=True
else:
b=False
I am having some trouble to write def main.
def palindrome(num):
return str(num) == str(num)[::-1]
Integer numbers don't have len().
Testing if a number is a palindrome is as simple as testing if the number is equal to its reverse (though if you want maximum efficiency you can just compare characters from both ends of the string until you reach the middle).
To find the reverse of an integer you can either do it the hard way (using mod % and integer division // to find each digit and construct the reverse number):
def reverse(num):
rev = 0
while num > 0:
rev = (10*rev) + num%10
num //= 10
return rev
Or the easy way (turning the number into a string, using slice notation to reverse the string and turning it back to an integer):
def reverse(num):
return int(str(num)[::-1])
This is an unreadable one-line recursive implementation based in part on the answer by pedrosorio.
def reverse(i):
return int(i!=0) and ((i%10)*(10**int(math.log(i,10))) + reverse(i//10))
def is_palindrome(i):
return i == reverse(i)
It works for integer i ≥ 0.
Note that reverse(123) == reverse(1230) == 321. This is not a problem, considering any nonzero integer that ends with 0 cannot be a palindrome anyway.
Note also that complete reversal of the integer may of course not be necessary to determine if it's a palindrome. The reversal may be implemented so as to be aborted early if the number is determined to not be a palindrome.
Long but readable:
def palindrome(x):
a=""
x=str(x)
for i in range(len(x),0,-1):
a+=x[i-1]
print a
if a==x:
return True
else:
return False
Reverse an integer and determine if it is a palindrome:
Convert integer to string.
Use reverse function to reverse the string and join it.
Check if reversed number = original number with if else condition.
See code:
number = 1221
reverse = ''.join(reversed(str(number)))
print(reverse)
if (int(reverse) == number):
print("number is Palindrome")
else:
print("number is not Palindrome")
def revers(num):
rev = 0
while num > 0:
rem = num % 10
rev = (rev * 10) + rem
num = num // 10
return rev
I used a list for this program, works with strings too.
print('Enter Something')
a = list(input())
for i in range ((len(a)),0,-1):
print (a[i-1],end='')
import math
a = raw_input("Enter number:")
n = -1
reverse = 0
for i in a:
n += 1
digit = math.pow(10,n)
reverse = int(i)*digit + reverse
print int(reverse)
if int(reverse) == int(a):
print "Palindrome"
else:
print ":("
This code converts int to String and then checks if the string is pallindrome. The advantage is that it is fast, the disadvantage being that it converts int to String thereby compromising with the perfect solution to question.
It handles negative int as well.
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
s = str(x)
if x >=0 :
if s == s[::-1]:
return True
else:
return False
else:
return False
t=int(input("enter nos of test cases= "))
while t>0:
n=int(input("enter number="))
rev=0
while n>0:
digit=n%10
rev=rev*10+digit
n=n//10
print(rev)
t-=1
Here is my solution.
z=input('input number')
if int(z) == int(str(z)[::-1]):
print('The number is palindrome')
else:
print('The number is not palindrome')
def pal_num(num):
if num<0:
print(False)
elif num == int(str(num)[::-1]):
print(True)
else:
print(False)
This example quickly takes care of the negative number edge case
I try to come out with this myself.
def number():
n = int(input("Enter a number: "))
return n
def reverse(n):
total = ""
while n > 0:
a = n % 10
n//= 10
total+= str(a)
return total
def palindrome (n):
total = 0
while n > 0:
a = n % 10
n//= 10
total+= a
if total == n:
x = "This number has a palindrome"
else:
x = ""
return x
n = number()
print (reverse(n))
print (palindrome(n))
original = raw_input("Enter a no = ") #original = number entered by user
rev = original[::-1] #rev = reverse of original by useing scope resolution
print 'rev of original no =',rev
if original == rev:
print "no's are equal"
else:
print "no's are not equal"

Categories

Resources