Using Python to convert integer to binary - python

I'm trying to convert integer to binary. This is my work.
I don't know how the make a list to show the binary.
num_str = input("Please give me a integer: ")
num_int = int(num_str)
while num_int > 0:
if num_int % 2 == 0:
num_int = int(num_int / 2)
num_remainder = 1
print("The remainder is:", 0)
continue
elif num_int % 2 == 1:
num_int = int(num_int / 2)
num_remainder = 1
print("The remainder is:", 1)
continue
How to make the remainder together?

Are you aware of the builtin bin function?
>>> bin(100)
'0b1100100'
>>> bin(1)
'0b1'
>>> bin(0)
'0b0'

You are on the right track, you just need to save the digits in a variable somewhere instead of just printing them to the screen:
num_str = input("Please give me a integer: ")
num_int = int(num_str)
num_bin_reversed = ''
while num_int > 0:
if num_int % 2 == 0:
num_int = int(num_int / 2)
num_remainder = 1
print("The remainder is:", 0)
num_bin_reversed += '0'
elif num_int % 2 == 1:
num_int = int(num_int / 2)
num_remainder = 1
print("The remainder is:", 1)
num_bin_reversed += '1'
num_bin = num_bin_reversed[::-1]
if int(num_str) > 0:
assert '0b' + num_bin == bin(int(num_str))
Now, try to fix it by making it work with negative numbers and 0 too!

#First off yes there is an easier way to convert i.e bin(int) but where is the fun in that
"""First we ask the user to input a number. In Python 3+ raw input is gone
so the variable integer_number will actually be a string"""
integer_number = input('Please input an integer') #get integer whole number off user
"""We could use int(input('Please input an integer')) but we don't want to overload
anyones brains so we show casting instead"""
'''Next we convert the string to an integer value (cast). Unless the user enters text
then the program will crash. You need to put your own error detection in'''
integer_number = int(integer_number)
"""initialise a variable name result and assign it nothing.
This so we can add to it later. You can't add things to a place that doesn't exist"""
result = ''
'''since we are creating an 8bit binary maximum possible number of 255
we set the for loop to 8 (dont forget that x starts at 0'''
for x in range(8):
#The variable in the for loop will increase by 1 each time
#Next we get the modulos of the integer_number and assign it to the variable r
r = integer_number % 2
#then we divide integer number by two and put the value back in integer_value
#we use // instead of / for int division els it will be converted to a float point variable
integer_number = integer_number//2
#Here we append the string value of r which is an integer to result
result += str(r)
#This then loops back to the for loop whilst x<8
#then we assign the reverse of result using [::-1] to result
result = result[::-1]
#print out the result
print(result)

You can store the remainders as digits in a string. Here is one possible function to convert from decimal to binary:
def dec2bin(d_num):
assert d_num >= 0, "cannot convert negative number to binary"
if d_num == 0:
return '0'
b_num = ""
while d_num > 0:
b_num = str(d_num%2) + b_num
d_num = d_num//2
return b_num

#This is the same code as the one above it's just without comments
#This program takes a number from the user and turns it into an 8bit binary string
integer_number = int(input('Please input an integer'))
result = ''
for x in range(8):
r = integer_number % 2
integer_number = integer_number//2
result += str(r)
result = result[::-1]
print(result)

here is a code that works in python 3.3.0 the converts binary to integer and integer to binary, JUST COPY AND PASTE!!!
def B2D():
decnum = int(input("Please enter a binary number"), 2)
print(decnum)
welcome()
def D2B():
integer_number = input('Please input an integer')
integer_number = int(integer_number)
result = ''
for x in range(8):
r = integer_number % 2
integer_number = integer_number//2
result += str(r)
result = result[::-1]
print(result)
welcome()
def welcome():
print("*********************************************************")
print ("Welcome to the binary converter program")
print ("What would you like to do?")
print ("Type 1 to convert from denary to binary")
print ("Type 2 to convert from binary to denary")
print ("Type 3 to exit out of this program")
choice = input("")
if choice == '1':
D2B()
elif choice == '2':
B2D()
elif choice == '3':
print("Goodbye")
exit
welcome()

I give thanks to nikpod. His code helped me give out my own answer.
Hope this helps.
# Define your functions here.
def int_to_reverse_binary(num):
string = ''
while num > 0:
string += str(num % 2)
num = num // 2
return string
def string_reverse(string_to_reverse):
return string_to_reverse[::-1]
if __name__ == '__main__':
# Type your code here.
# Your code must call int_to_reverse_binary() to get
# the binary string of an integer in a reverse order.
# Then call string_reverse() to reverse the string
# returned from int_to_reverse_binary().
num = int(input())
binary = int_to_reverse_binary(num)
print(string_reverse(binary))

Sheesh some of these examples are very complicated for a Python noob like me.
This is the way I did the lab(Please let me know what you think):
First, the way the lab wants to see it is in reverse(not correct binary but that's the way the lab wants to see it):
x = int(input())
bin_number = ''
while x > 0:
result = x % 2
bin_number = str(bin_number) + str(result)
x = x // 2
if x < 1:
break
continue
print(bin_number)
Second, prints the result in the correct order(but incorrect for the lab)
x = int(input())
bin_number = ''
while x > 0:
result = x % 2
bin_number = str(bin_number) + str(result)
rev_bin_number = bin_number[::-1]
x = x // 2
if x < 1:
break
continue
print(rev_bin_number)

Related

Python-using FOR loop to compare pairs of integers

I am taking a basic course in Python and have difficulty on solving the following task (NOTE: I can only use FOR loops and IF statements as that is what we have learned so far):
The user has to enter 2*n numbers, where "n" is input from the user.
Then the 1st and 2nd number form a pair as do the 3rd and 4th and so on.
I have to write simple code which compare if all pairs have the same value and if not to calculate the max difference between 2 consequent pairs.
If all pairs have equal value I must print "Yes, value={Value}". If not, I must print "No, maxdiff={Difference}".
Currently I have written the following (which doesn't work):
count_numbers = int(input()) * 2
sum_pair1 = 0
sum_pair2 = 0
result = 0
for i in range(0, count_numbers * 2, 2):
sum_pair1 = int(input()) + int(input())
sum_pair2 = int(input()) + int(input())
if sum_pair1 == sum_pair2:
result = f"Yes, value ={sum_pair1}"
else:
result = f"No, maxdiff={abs(sum_pair1 - sum_pair2)}"
print(result)
Tried writing code but cannot get it right.
I used max_diff to keep track of maximal difference and are_all_equal to tell whether all numbers are equal.
max_diff = 0
last_number = None
are_all_equal = True
# How many numbers would you like to enter?
numbers_count = int(input())
for _ in range(numbers_count):
number1 = int(input())
number2 = int(input())
if are_all_equal:
if number1 == number2:
if last_number and last_number != number1:
are_all_equal = False
last_number = number1
else:
are_all_equal = False
diff = abs(number1 - number2)
if diff > max_diff:
max_diff = diff
if are_all_equal:
print(f"Yes, value = {last_number}")
else:
print(f"No, maxdiff = {max_diff}")

Loop and check if integer

I have an exercise:
Write code that asks the user for integers, stops loop when 0 is given.
Lastly, adds all the numbers given and prints them.
So far I manage this:
a = None
b = 0
while a != 0:
a = int(input("Enter a number: "))
b = b + a
print("The total sum of the numbers are {}".format(b))
However, the code needs to check the input and give a message incase it is not an integer.
Found that out while searching online but for the life of me I cannot combine the two tasks.
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
else:
total_sum = total_sum + num
print(total_sum)
break
I suspect you need an if somewhere but cannot work it out.
Based on your attempt, you can merge these two tasks like:
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
try:
a = int(a)
except ValueError:
print('was not an integer')
continue
else:
b = b + a
print("The total sum of the numbers are {}".format(b))
If you want to use an If-Statement, you don't need the else: If the number is not 0 it will just start again until it's 0 sometime.
total_sum = 0
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
total_sum = total_sum + num
if num == 0:
print(total_sum)
break
Since input's return is a string one can use isnumeric no see if the given value is a number or not.
If so, one can convert the string to float and check if the given float is integer using, is_integer.
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
if a.isnumeric():
a = float(a)
if a.is_integer():
b += a
else:
print("Number is not an integer")
else:
print("Given value is not a number")
print("The total sum of the numbers are {}".format(b))

The last value in my list will not convert into integer

I am writing a code in which I take values from a user until they enter 'q'. I then have to print the EVEN numbers out in ascending order. I how to do the program, I just have run into a minor problem I do not know how to solve.
My code is:
integer = []
g = 7
while g > 1: # Initiate loop
num = input('Enter an integer or press q to quit. ')
if num == 'q':
break
integer = list(map(int, integer))
if num % 2 == 0:
integer.append(num)
integer.sort()
print(integer)
Running this code gives me the error that not all strings have converted. So I then erased the second if statement:
if num % 2 == 0:
integer.append(num)
Erasing this I can see that the last value in the list will not convert into an integer. I do not know why that is and I have tried numerous string-list to integer-list conversions and they all never convert the last value. Does anybody know why this is?
you can do this:
evens = []
while True: # Initiate infinite loop
num = input('Enter an integer or press q to quit. ')
if num == 'q':
break
num = int(num) #convert the num to int
if num % 2 == 0:
evens.append(num)
evens.sort()
print(evens)
Corrected code:
integer = []
g = 7
while g > 1: # Initiate loop
num = input('Enter an integer or press q to quit. ')
if num == 'q':
break
num = int(num) #convert input to integer
if num % 2 == 0:
integer.append(num)
integer.sort()
print(integer)
the issue is num is a string from user input, you must convert it to an integer like this
if int(num) % 2 == 0:
integer.append(int(num))

how can i return a changing int within a string in python?

the function i am working on is supposed to tell a user whether a number they have given is a perfect number or not (i.e. is equal to half the sum of its factors). if a user gives the number 8, the output should look like this:
8 is not a perfect number
but i can't figure out what to put in the return statement to make the int, which changes depending on the user input, print out with the string. the code so far looks like this:
#the code is within another larger function which is the reason for the elif
elif(message == 2):
num1 = int(input("""Please enter a positive integer :"""))
while(num1 <= 0):
print("Number not acceptable")
num1 = int(input("""Please enter a positive integer :"""))
thisNum = isPerfect(num1)
if(thisNum == True):
return num1, is a perfect number
elif(thisNum == False):
return num1 is not a perfect number
def isPerfect(num1):
sumOfDivisors = 0
i = 0
listOfDivisors = getFactors(num1)
for i in range(0, len(listOfDivisors) - 1):
sumOfDivisors = sumOfDivisors + listOfDivisors[i]
i += 1
if(sumOfDivisors / 2 == num1):
return True
else:
return False
if i were to do return(num1, "is not a perfect number") it would come out like
(8, 'is not a perfect number')
return "%d is not a perfect number" % number
You can do this with string formating using %s. Anyway there is some other ways as describes String Formating Operators
convert the integer to a string and concatenate the rest of your statement:
return str(num1) + ' is not a perfect number'
You can use the .format() mini language, and at the same time, simplify your code:
elif(message == 2):
num1 = int(input("""Please enter a positive integer :"""))
while(num1 <= 0):
print("Number not acceptable")
num1 = int(input("""Please enter a positive integer :"""))
if isPerfect(num1):
return '{} is a perfect number'.format(num1)
else:
return '{} is not a perfect number'.format(num1)
Also in your other method, simply return the result of the comparison:
def isPerfect(num1):
sumOfDivisors = 0
listOfDivisors = getFactors(num1)
for i listOfDivisors:
sumOfDivisors += i
#if(sumOfDivisors / 2 == num1):
# return True
#else:
# return False
return sumOfDivisors / 2 == num1
Also, I would suggest having a read of PEP-8, which is the style guide for Python.

The Next Palindrome number

I am beginner in programming, So can you please tell me what's wrong with my code?
I want to print next palindrome number if the number entered by the user (n) is not palindrome
n = int(input("Enter any number :- "))
reverse = 0
temp = n
while (n!=0):
reverse = reverse * 10
reverse = reverse + n%10
n=n//10
if(temp==reverse):
print ("Already palindrome:: ")
if(temp != reverse):
new_temp = temp
new_reverse = 0
for i in range(new_temp,new_temp+10):
while(temp != 0):
new_reverse = new_reverse * 10
new_reverse = new_reverse + temp%10
temp = temp//10
if(new_temp==new_reverse):
print ("Next pallindrome is :- ",new_temp)
break
if(new_temp != new_reverse):
temp = new_temp+1
There are two problems with your code.
1) Your "for i in range" loop calculates the reverse of the temp variable, but you don't change the temp variable's value.
You do
new_temp = temp
for i in range(new_temp,new_temp+10):
[SNIP]
if(new_temp != new_reverse):
temp = new_temp+1 #this value never changes.
So you're making 10 iterations with one and the same value.
2) Ten iterations might not be enough to find a palindrome. Keep going until you find a palindrome.
Working code:
def reverse(num):
reverse= 0
while num:
reverse= reverse*10 + num%10
num= num//10
return reverse
num= int(input("Enter any number :- "))
if num==reverse(num):
print ("Already palindrome.")
else:
while True:
num+= 1
if num==reverse(num):
print ("Next palindrome is : %s"%num)
break
To check if a number is a palindrome, you don't need to convert it to a number. In fact, its a lot simpler if you just check the string equivalent of your number.
>>> i = '212'
>>> i == i[::-1]
True
>>> i = '210'
>>> i == i[::-1]
False
Use this to your advantage, and create a function:
def is_palindrome(foo):
return str(foo) == str(foo)[::-1]
Next, to find the next palindrome, simply increment the number till your palindrome check is true.
Combine all that, and you have:
def is_palindrome(n):
return str(n) == str(n)[::-1]
n = raw_input('Enter a number: ')
if is_palindrome(n):
print('Congratulations! {0} is a palindrome.'.format(n))
else:
n1 = n
while not is_palindrome(n1):
n1 = int(n1)+1
print('You entered {0}, but the next palindrome is {1}'.format(n, n1))
Here is how it works:
$ python t.py
Enter a number: 123
You entered 123, but the next palindrome is 131
$ python t.py
Enter a number: 121
Congratulations! 121 is a palindrome.
If it helps, I believe it's possible to solve this problem with n/2 iterations where n is the length of the input number. Here's my solution in Python:
def next_palin_number(number):
number+=1
# Convert the number to a list of its digits.
number = list(str(number))
# Initialize two indices for comparing symmetric digits.
i = 0
j = len(number) - 1
while i < j:
# If the digits are different:
if number[i] != number[j]:
# If the lower-power digit is greater than the higher-power digit:
if int(number[j]) > int(number[i]):
if number[j-1]!='9':
number[j - 1] = str(int(number[j - 1]) + 1)
number[j] = number[i]
else:
number = list(str(int(''.join(number[:j]))+1))+number[j:]
else:
number[j] = number[i]
i += 1
j -= 1
# Concatenate and return the result.
return "".join(number)
This problem has a wonderful number of ways to solve them.
One of them is
def nearest_palindrome(number):
#start writitng your code here
while True:
number+=1
if str(number) == str(number)[::-1]:
return number
number=12300
print(nearest_palindrome(number))
Thanks for your time to read my answer : )
I have written this for finding next pallindrome number given a pallindrome number.
def palindrome(num):
bol=False
#x=len(str(num))
num=num+1
while(bol==False):
if(check_palindrome(num)):
bol=True
else:
num=num+1
return num
def check_palindrome(n):
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
return True
b=palindrome(8)
print(b)
def next_palin_drome(n):
while True:
n+=1
if str(n) == str(n)[::-1]:
return n
n=12231
print(next_palin_drome(n))
output:12321
def nearest_palindrome(number):
for i in range(1,number):
number=number+1
tem=str(number)
tem1=tem[-1::-1]
if(tem==tem1):
return number
else:
continue
number=12997979797979797
print(nearest_palindrome(number))
def nearest_palindrome(number):
n = len(str(number))//2
if(len(str(number)) % 2 == 0):
#number like 1221
number_1 = int((str(number))[:n]) #12
number_2 = int((str(number))[n:]) #21
if(number_1 < number_2):
number_1 += 1
number_2 = int(str(number_1)[::-1])
else:
number_2 = int(str(number_1)[::-1])
# if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(number_1)[::-1]
#combining the both parts
ans = int(str(number_1) + str(number_2))
return ans
else:
#numer like 12510 n=2
nu = int((str(number))[:n+1]) #add in this number
number_1 = int((str(number))[:n]) # 12
number_2 = int((str(number))[n+1:]) # 21
if (number_1 < number_2):
nu += 1
number_2 = int((str(nu))[::-1][1:])
else:
number_2 = int((str(nu))[::-1][1:])
#if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(nu)[::-1]
number_2 = number_2[1:]
#combinning both parts
ans = int(str(nu) + str(number_2))
return ans
number=12331
print(nearest_palindrome(number))
If a definite range is given:
# function to check if the number is a palindrome
def palin(x):
s=str(x)
if s==s[::-1]:
return True
else:
return False
n=int(input("Enter the number"))
# Putting up range from the next number till 15 digits
for i in range(n+1,int(10e14)):
if palin(i) is True:
print(i)
break
A brute force method:
def math(n):
while not var:
n += 1
if str(n) == str(n)[::-1] : f = 'but next is : '+str(n); return f
n = int(input()); t = math(n); print('Yes',t) if str(n) == str(n)[::-1] else print('No',t); global var; var = False
This is a good fast solution. I saw that the other solutions were iterating and checking through every +1 they did, but this is really slow for big numbers.
This solution has O(n) time if you look at the length of the number
beginNumber = 123456789101112131415161718 #insert number here for next palidrome
string = str(beginNumber + 1)
length = len(string)
number= [int(x) for x in list(string)]
for i in range(length//2):
if (number[i] != number[length-1-i]):
if (number[i]<number[length-1-i]):
number[length-2-i] += 1
number[length-1-i] = number[i]
print("".join([str(x) for x in number]))
I have written this for finding next pallindrome number given a pallindrome number..
#given a pallindrome number ..find next pallindrome number
input=999
inputstr=str(input)
inputstr=inputstr
#append 0 in beginning and end of string ..in case like 99 or 9999
inputstr='0'+inputstr+'0'
length=len(inputstr)
halflength=length/2;
#if even length
if(length%2==0):
#take left part and reverse it(which is equal as the right part )
temp=inputstr[:length/2]
temp=temp[::-1]
#take right part of the string ,move towards lsb from msb..If msb is 9 turn it to zero and move ahead
for j,i in enumerate(temp):
#if number is not 9 then increment it and end loop
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now you have right hand side...mirror it and append left and right part
output=temp[::-1]+temp
#if the length is odd
if(length%2!=0 ):
#take the left part with the mid number(if length is 5 take 3 digits
temp=inputstr[:halflength+1]
#reverse it
temp=temp[::-1]
#apply same algoritm as in above
#if 9 then make it 0 and move on
#else increment number and break the loop
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now the msb is the middle element so skip it and copy the rest
temp2=temp[1:]
#this is the right part mirror it to get left part then left+middle+right isoutput
temp2=temp2[::-1]
output=temp2+temp
print(output)
similarly for this problem take the left part of given number ...reverse it..store it in temp
inputstr=str(number)
if(inputstr==inputstr[::-1])
print("Pallindrome")
else:
temp=inputstr[:length/2]
temp=temp[::-1]
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
now depending on length of your number odd or even generate the output..as in the code
if even then output=temp[::-1]+temp
if odd then temp2=temp1[1:]
output=temp2[::-1]+temp
I am not sure about this solution..but hope it helps

Categories