Binary and Denary converter in python - 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')

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.

Concatenate the numbers between 1 and N and see if it is divisible by 3

I'm trying to make a program that basically works like this:
I ask for a number, and from that number I must form a number N by concatenating all the numbers between 1 and N. For example, if I enter a 12, the number N will be 123456789101112, or if I enter a 6, the number would be 123456. Once N has been formed, I must return "YES" on the screen in the case that N is divisible by 3 and “NO” in the case that it is not.
This is what I have:
n = int(input("Enter a number:"))
for x in range (n + 1):
if(n%3==0):
print("YES")
else:
print("NO")
I just started using Python and I don't know what I'm doing wrong, if someone can give me a hand I would be very grateful!
The answer will be :
if n%3 != 1:
print("YES")
else:
print("NO")
Reason
Every number is one of the three types (3*k+1), (3*k+2) or (3*k). A number is divisible by 3 if the sum of its digits is divisible by 3 a.k.a. it is a (3*k) type of number.
If input is 1. Then N will be 1 which is a (3*k+1) type of number so it is not divisible by 3.
When input is 2. Then N will be 12 which is divisible by 3.
When input is 3. Then N will be 123 which is divisible by 3.
Similarly, when input is 4. Then N will be 1234 which is not divisible by 3.
If you go one you realise that N will be divisible by 3 whenever the input is not a (3*k+1) type of number.
If you want to do it using the algorithm you describe, then a simple (but not very fast) way of doing it would be so:
n = int(input("Enter a number:")) # get the number
stringNumber = ""
for x in range(1, n+1):
stringNumber += str(x) # join the string version of numbers 1...n into a string
intNumber = int(stringNumber) # convert the string concatenation into an int
if (intNumber % 3 == 0): # check if the int is divisible by 3
print("YES")
else:
print("NO")
You can speed-up the string concatenation by using join() if you wish:
stringNumber = "".join([str(digit) for digit in range(1,n+1)])
the result is the same
However, you might also notice that a number is divisible by 3 if the sum of its digits is divisible by 3, so you can use an algorithm like this:
n = int(input("Enter a number:")) # get the number
sumOfDigits = sum([digit for digit in range(1,n+1)]) # sum numbers 1...n
if (sumOfDigits % 3 == 0): # check if the int is divisible by 3
print("YES")
else:
print("NO")
Here is one possible solution. It shows how you can test n the input and val the concatenated value
n = int(input("enter a number: "))
# This line creates a list of numbers and
# then concatenates them as a new number in string format
val = "".join(str(x) for x in range(1, n + 1))
print(f"Is {n} divisible by 3? ")
print("no" if int(n) % 3 else "yes")
print(f"Is {val} divisible by 3? ")
print("no" if int(val) % 3 else "yes")
You can write a one-line tertiary operation with a list comprehension to do this as well.
def check():
n = int(input("Enter a number:"))
return 'Yes' if int(''.join([str(i) for i in range(1,n+1)]))%3==0 else 'No'
check()
Enter a number:12
'Yes'
Use a range to produce numbers from 1 to N, convert them to strings and concatenate them:
x = 12
N = int("".join(map(str,range(1,x+1))))
div3 = N%3 == 0
print("Is",N,"divisible by 3?",["NO","YES"][div3])
# Is 123456789101112 divisible by 3? YES

Decimals to binary in 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*)

Python Program to check if a number is armstrong or not is not working, what am I doing wrong?

n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)

Checking to see if a string is an integer or float

So I'm creating a program to show number systems, however I've run into issues at the first hurdle. The program will take a number from the user and then use that number throughout the program in order to explain several computer science concepts.
When explaining my first section, number systems, the program will say what type of number it is. I'm doing this by converting the string into a float number. If the float number only has '.0' after it then it converts it into a integer.
Currently I'm using this code
while CorrectNumber == False:
try:
Number = float(NumberString) - 0
print (Number)
except:
print ("Error! Not a number!")
This is useful as it shows if the user has entered a number or not. However I am unsure how to now check the value after the decimal place to check if I should convert it into a integer or not. Any tips?
If the string is convertable to integer, it should be digits only. It should be noted that this approach, as #cwallenpoole said, does NOT work with negative inputs beacuse of the '-' character. You could do:
if NumberString.isdigit():
Number = int(NumberString)
else:
Number = float(NumberString)
If you already have Number confirmed as a float, you can always use is_integer (works with negatives):
if Number.is_integer():
Number = int(Number)
Not sure I follow the question but here is an idea:
test = ['1.1', '2.1', '3.0', '4', '5', '6.12']
for number in test:
try:
print(int(number))
except ValueError:
print(float(number))
Returns:
1.1
2.1
3.0
4
5
6.12
Here is the method to check,
a = '10'
if a.isdigit():
print "Yes it is Integer"
elif a.replace('.','',1).isdigit() and a.count('.') < 2:
print "Its Float"
else:
print "Its is Neither Integer Nor Float! Something else"
This checks if the fractional-part has any non-zero digits.
def is_int(n):
try:
float_n = float(n)
int_n = int(float_n)
except ValueError:
return False
else:
return float_n == int_n
def is_float(n):
try:
float_n = float(n)
except ValueError:
return False
else:
return True
Testing the functions:
nums = ['12', '12.3', '12.0', '123.002']
for num in nums:
if is_int(num):
print(num, 'can be safely converted to an integer.')
elif is_float(num):
print(num, 'is a float with non-zero digit(s) in the fractional-part.')
It prints:
12 can be safely converted to an integer.
12.3 is a float with non-zero digit(s) in the fractional-part.
12.0 can be safely converted to an integer.
123.002 is a float with non-zero digit(s) in the fractional-part.
Regular expressions are nice for this as they can be custom tailored in case you have some edge-cases. For example:
How do you want to handle padded numbers (numbers with leading zeros). My example here includes this consideration.
Do you need to handle exponents, e.g. 2.3E12 or 2.3e12. This is not handled here.
...in other words, if your implementation doesn't agree with an assumption mine makes, you can change it.
Regular expressions work in all versions of Python (and other languages). They can be compiled for reuse, so should be pretty quick.
# Int is:
# - Only numbers that do NOT start with 0 (protect padded number strings)
# - Exactly 0
re_int = re.compile(r"(^[1-9]+\d*$|^0$)")
# Float is:
# - Only numbers but with exactly 1 dot.
# - The dot must always be followed number numbers
re_float = re.compile(r"(^\d+\.\d+$|^\.\d+$)")
These tests all pass:
def test_re_int(self):
self.assertTrue(re_int.match("1"))
self.assertTrue(re_int.match("1543"))
self.assertTrue(re_int.match("0")) # Exactly 0 is good
self.assertFalse(re_int.match("1.54"))
self.assertFalse(re_int.match("1a4"))
self.assertFalse(re_int.match("14a"))
self.assertFalse(re_int.match("a14"))
self.assertFalse(re_int.match("00")) # Ambiguous
self.assertFalse(re_int.match("0012")) # Protect padding
def test_re_float(self):
self.assertTrue(re_float.match("1.0"))
self.assertTrue(re_float.match("1.456"))
self.assertTrue(re_float.match("567.456"))
self.assertTrue(re_float.match("0.10"))
self.assertTrue(re_float.match(".10"))
self.assertFalse(re_float.match("1.0.0")) # Too many dots
self.assertFalse(re_float.match(".10.0"))
self.assertFalse(re_float.match("..034"))
self.assertFalse(re_float.match("1"))
self.assertFalse(re_float.match("0"))
self.assertFalse(re_float.match("1a4"))
self.assertFalse(re_float.match("14a"))
self.assertFalse(re_float.match("a14"))
self.assertFalse(re_float.match("1.a4"))
self.assertFalse(re_float.match("1.4a"))
self.assertFalse(re_float.match(".a14"))
Please comment if there are any caveats, missing details or regular expression improvements I can make.
Here's my gist that not only checks for positive & negative ints, but also checks for positive & negative floats. It also checks if the string is just a normal non-number.
def int_float_or_string(string):
try:
int(string) # strict and nice
except ValueError:
if is_strictly_float(string): # float() is too permissive, this is better
return "float"
else:
return "string"
else:
return "int"
def is_strictly_float(string):
if string.startswith("-"):
string = string[1:]
return "." in string and string.replace(".", "", 1).isdecimal()
int() is great for checking an integer, but float() has a problem of being too laid back in what it calls a float.
x=input("Enter a value to check it's type: ")
def checknumber(a):
try:
a=float(a)
if int(a)/a==1:
print("This is Integer")
return a
elif a/int(a)>1:
print("This is Float")
return a
except ValueError:
print("This value is String")
return str(a)
x=checknumber(x)```
I rewrite bin Mohammed's answer as follows (number also may be negative):
from numpy import nan, isnan
def is_valid_number(s):
if (s.find('-') <= 0) and s.replace('-', '', 1).isdigit():
if (s.count('-') == 0):
s_type = 'Positive Integer'
else:
s_type = 'Negative Integer'
elif (s.find('-') <= 0) and (s.count('.') < 2) and \
(s.replace('-', '', 1).replace('.', '', 1).isdigit()):
if (s.count('-') == 0):
s_type = 'Positive Float'
else:
s_type = 'Negative Float'
else:
s_type = "Not alphanumeric!"
return('{}\t is {}'.format(s, s_type))
example:
nums = ['12', '-34', '12.3', '-12.0', '123.0-02', '12!','5-6', '3.45.67']
for num in nums:
print(is_valid_number(num))
result:
12 is Positive Integer
-34 is Negative Integer
12.3 is Positive Float
-12.0 is Negative Float
123.0-02 is Not alphanumeric!
12! is Not alphanumeric!
5-6 is Not alphanumeric!
3.45.67 is Not alphanumeric!
minimal code:
from numpy import nan, isnan
def str2num(s):
if (s.find('-') <= 0) and s.replace('-', '', 1).isdigit():
return(int(s))
elif (s.find('-') <= 0) and (s.count('.') < 2) and \
(s.replace('-', '', 1).replace('.', '', 1).isdigit()):
return(float(s))
else:
return(nan)
example:
nums = ['12', '-34', '12.3', '-12.0', '123.0-02', '12!','5-6', '3.45.67']
for num in nums:
x = str2num(num)
if not isnan(x):
print('x =', x) # .... or do something else
result:
x = 12
x = -34
x = 12.3
x = -12.0

Categories

Resources