Condition for Binary number or not - python

Am trying to make a simple program to convert binary number to decimal number. I'd like to first write a condtion whether to check the given number is a binary or not. How do i do that?
Except that, the program works normally without any errors but am afraid when a non binary number is given, it still does the job.Input
print("Binary to Decimal")
bin = input("Give a binary number : ")
bin = [int(i) for i in bin]
powers = [i for i in range(len(bin)-1,-1,-1)]
for i in range(len(bin)):
bin[i] = bin[i] * 2**(powers[i])
decimal = sum(bin)
print("The corresponding Decimal digit is : %d"%(decimal))
Output
Binary to Decimal
Give a binary number : 101
The correspnding Decimal digit is : 5
Also if u find any corrections or want to make any suggestions, please feel free to suggest me below.

Try pythonic way is not to test, but to try the conversion and catch the exception if the input is bad. This is the Easier to ask for forgiveness than permission prinicple:
b = input("Give a binary number : ")
try:
print(int(b, 2))
except ValueError:
print("not binary")
If you still want to check an easy test is to use all():
if all(n in ('1','0') for n in b):
# it's all 1's and 0's

You can check that if the string contains any other number rather than 0's and 1's then it is not a binary number.

you can check with regular expression
import re
if re.match("^[01]+$", '011001'):
//then proceed
else:
//do something for non-binary

Related

Converting decimal numbers to binary in python using a 2D list

I'm trying to write a code in python which will take a number as input which will define how much bits I want to represent each number in, and then print out all the numbers that that number of bits can represent in binary which will be integer value in a list. For example:
Input :
Enter the number of bits : 3
Output :
[[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]
Try this out:
num_bits = input("How many bits?")
bits_list = [ list(map(int, str('{0:0'+num_bits+'b}').format(i))) for i in range(2**int(num_bits))]
print(bits_list)

How to keep leading zero when returning value from modulo Python

I want to build a program which allows the user to input a number then make that number exponent of 2. Also user inputs how many last digits of final number wants to see. This is my code:
exponent = eval(input('Type in exponent '))
lastDigits = eval(input('Type in how many digits you want to see'))
number = 2**exponent
print(number /int(('1'+('0'*lastDigits))))
The output for example is:
Type in exponent = 10
Type in how many digits you want to see = 3
Here comes the problem.
If my exponent is 10 that means 2**10 = 1024
I want to see 3 last digits so that is 024 but Python doesn't keep this leading zero so I just get 24. How can I fix this?
I would use string operations instead of integer operations:
exponent = int(input('Type in exponent '))
lastDigits = int(input('Type how many digits you want to see '))
number = 2 ** exponent
cropped = str(number)[-lastDigits:]
print(cropped) # Result: "024"
I'm essentially just slicing off all but the last lastDigits characters in the string representation of number, that way we include any leading zeroes.
I also switched to using int casting instead of the eval function, because the eval function could be potentially dangerous if anyone decides to put something destructive into the input.

How to get a irrational number as a user input in python?

How to get a irrational number as a user input in python? Like squared root of 2
something like :
Irrational_Number = float(input("ENTER a Irrational Number : "))
>>> ENTER a Irrational Number : (USER INPUT)
and then user put a Number like N-th root of K (i mean the number in this format not the exactly this kind of String) " Pi " , " e " or " Phi " in command Line.
How User Can do this Directly in command line python (3.8)
I searched this question everywhere but there is nothing about that...
First of all, you're casting your input to a float, so to be precise (which is important if we're bandying around terms like Irrational Number) then we have to highlight the assumption that were talking about approximations to Irrational Numbers here.
That done, there's a few ways you can explore a solution:
The first would be to define a namespace in which you map string names to numeric equivalents - a simple dict could do the trick, like:
numbers_as_words = { "e",2.718281828459045
"pi",3.141592653589793
"phi",1.618033988749895
"sqr2",1.4142135623730951
"feet_to_meters",0.3048
"lbs_to_kg",0.453592
"miles_to_kilometers",1.60934
"gallons_to_litres",3.78541 }
I've padded that out with some non-irrational place-holders too, in case you wanted to embed some simple conversion type logic.
Then, you'd need to take your input as a string, perform a simple replace function on the string to resolve any matching strings, and viola , you've got a mixed numeric/string input method.
def replace_names_and_return_float(user_input, mapping):
for k,v in mapping.items():
user_input = user_input.replace(k,str(v))
return float(user_input)
Irrational_Number = replace_names_and_return_float(input("ENTER a Irrational Number : "), numbers_as_words )
Then it's just up to you to maintain that numbers_as_words dictionary to contain all the substitutions you want to recognise. That could get tedious, but it ought to be enough to get you started.
If you find some official list of irrational number approximations, you might be able to download it, and construct a numbers_as_words mapping as an automated process, but I've not Googled that just now.
Please find below code snippet:
import re
g = input("Enter your irrational number : ")
if g=='pi':
g=math.pi
elif "root" in g:
root=float(re.search('[0-9]+', g).group())
number=float(re.search('(\d+)(?!.*\d)', g).group())
g=number**(1/float(root))
print(g)
Advantage of using this would be:
There is no manual value inserted
You can build it for every symbol present in math lib
Can be extended for other operations as well

Converting Binary to Decimal in python (without built in binary function)

Alrighty, first post here, so please forgive and ignore if the question is not workable;
Background:
I'm in computer science 160. I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced. We have been working in Python and each week we are prompted to write a program.
I have been working with this problem for over a week and am having a hard time even starting.
The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent. Now, I have gotten some tips from a classmate and it sent me at least in a direction.
Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.
I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.
setbitval = 0
counter = 0
user = int(input("enter a binary value. "))
if user % 2 == 1:
user = (user/10) - .1
setbitval += 1
This is all I've got so far.. My thinking is getting in the way. I've searched and searched, even through these forums.
Any information or thoughts are extremely appreciated,
T
Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.
for i in reversed(bits):
decimal += 2**counter * int(i)
counter += 1
This is the formula someone here gave me and I've been trying different iterations of "for i in bits: if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".
Any thoughts?
you can use this code:
binary= raw_input("Binary: ")
d= int(binary, 2)
print d
To convert binary value to decimal you need to do the following:
Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...
Let's say, for example you need to convert a number 1010 to decimal:
You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10
So in your python code, you need to:
read the int that the user inputted (representing the binary value).
convert that int and convert it to string, so you can break it into list of digits
make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)
go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0
Here's the code that demonstrates what I just tried to explain:
user_input = int(input("enter a binary value"))
bits = list(str(user_input))
decimal = 0
counter = 0
for i in reversed(bits):
decimal += 2**counter * int(i)
counter+=1
print 'The decimal value is: ', decimal
I'll agree this is close to the "code this for me" territory, but I'll try to answer in a way that gets you on the right track, instead of just posting a working code snippet.
A simple way of doing this is just to use int()'s base argument, but I'm guessing that is disallowed.
You already have a way of testing the current bit in your question, namely checking whether n % 2 == 1. If this is the case, we need to add a power of two.
Then, we need some way of going to the next bit. In binary, we would use bit shifts, but sadly, we don't have those. a >> b is equivalent to a // (2**b) - can you write a decimal equivalent to that?
You also need to keep a counter of which power of two the current bit represents, a loop, and some way of detecting an end condition. Those are left as exercises to the reader.
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number
The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.
Hopefully, this code clarifies things a bit.
x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)
This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:
1st element of binary number * 2^(length of binary number - 1)
2nd element of binary number * 2^(length of binary number - 2)
and so on till we get to the last element and ...2^0
If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.
This code, however, assumes that the binary number is valid. Let me know if it helps.
Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.
x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
decimal += int(x[index]) * 2**exp
index += 1
exp -= 1
print(decimal)
In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.
Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:
def is_binary(x):
""" Returns True if number x is binary and False otherwise.
input: x as a string
"""
for i in list(x):
if i not in ["1", "0"]:
return False
return True
def binary_decimal(x):
""" Converts binary to decimal.
input: binary number x as a string
output: decimal number as int
"""
if not is_binary(x):
return "Number is invalid"
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
return decimal
The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.
Of course, you can implement this solution without any functions.

using list operator "in" with floating point values

I have a list with floats, each number with 3 decimals (eg. 474.259). If I verify the number in the list like this:
if 474.259 in list_sample:
print "something!"
Then the message is shown, but if I take the number from another list and I round it:
number = other_list[10]
number = round(number, 3)
if number == 474.259:
print "the numbers are same!"
if number in list_sample:
print "something!"
The second message is not shown.
Comparing floating point numbers for exact equality usually won't do what you want. This is because floating point numbers in computers have a representation (storage format) which is inherently inaccurate for many real numbers.
I suggest reading about it here: http://floating-point-gui.de/ and doing something like a "fuzzy compare" using an "epsilon" tolerance value to consider the numbers equal so long as they differ by less than x% or whatever.
You could also following an approach, where you compare the values based on an arbitrary precision.
For example, convert all your floats like this:
def internalPrecision(number):
precision = 1000
return int(round(number * precision))
If you do this, both operators == and in should work.
You can use numpy.isclose() instead of Python's in.
import numpy as np
other_list = np.array([474.251001, 123.456])
number = other_list[0]
number = round(number, 3)
if number == 474.251:
print "number == 474.251"
if number in other_list:
print "number in other_list"
if any(np.isclose(number, other_list, rtol=1e-7)):
print 'any(np.isclose(number, other_list, rtol=1e-7))'
Output:
number == 474.251
any(np.isclose(number, other_list, rtol=1e-7))

Categories

Resources