Convert integers to binary, need to remove leading zero - python

I wrote a program to convert an integer to binary without using bin(). However, when executed, this function adds a leading zero.
def decimalToBinary(n):
def helper(n):
if n == 0:
return '0'
else:
if n%2 == 1:
binaryDigit = '1'
else:
binaryDigit = '0'
return helper(n//2) + binaryDigit
helper(n)
print(helper(n))
Output:
>>> decimalToBinary(100)
01100100
How can I change this so that when 100 is input, the output is 1100100, rather than 01100100?

Use empty string in if n == 0: return "" to skip this zero.
Only 0 needs "leading zero" so you have to use extra if to recognize this value and return 0
def decimalToBinary(n):
def helper(n):
if n == 0:
return '' # <- empty string
else:
if n%2 == 1:
binaryDigit = '1'
else:
binaryDigit = '0'
return helper(n//2) + binaryDigit
if n == 0:
result = '0' # <- "leading zero" only for `n == 0`
else:
result = helper(n)
print(result)
# --- test ---
for x in range(16):
decimalToBinary(x)

My suggestion would be
print(str(helper(n)).lstrip("0"))
or
print(str(helper(n))[1:])
unless helper(n) already returns a string, in this case remove str() in the examples.

Use some kind of trim function.
I believe in python you will find something similar to this:
trimStart("0") // example from C#
This is primitive method but will work for sure :)

Something I found somewhere, a long time ago in a galaxy far away:
n = 100
b = ''
while n > 0:
b = str(n % 2) + b
n >>= 1
print(b) # 1100100

Related

Add to polynomials

In this code there are four test cases. Three test cases are camed successfully but 4th test case was not getting expected output. Please help me.
I got 0x^3 as output in 4th test case but expected output is 0
Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B
Output
Print the addition of polynomials A and B.
If the degree of polynomial is zero and the constant term is also zero, then just print 0 to represent the polynomial.
For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.Explanation
We need all test cases can be came when code was run. I want exact outputs for all test cases
Here is the question and test case inputs and outputs in the below url link
https://drive.google.com/file/d/1DhE2akiG_pX_Q_EoKaEY9EapSgz3xWhY/view?usp=sharing
def check_polinom(polinom):
checked = []
while polinom:
tmp = polinom.pop(0)
if polinom:
for i in range(len(polinom)-1, -1, -1):
if polinom[i][0] == tmp[0]:
tmp[1] += polinom[i][1]
polinom.pop(i)
checked.append(tmp)
return checked
def add_polinoms(pol_1, pol_2):
added = []
while pol_1 or pol_2:
if pol_1:
tmp = pol_1.pop(0)
for i in range(len(pol_2)):
if pol_2[i][0] == tmp[0]:
tmp[1] += pol_2[i][1]
pol_2.pop(i)
break
else:
tmp = pol_2.pop(0)
added.append(tmp)
added.sort(reverse=True)
return(added)
def print_polinom(polinom):
s = ''
if polinom:
if polinom[0][1] < 0:
s += '-'
polinom[0][1] = -polinom[0][1]
if polinom[0][1] == 1:
if polinom[0][0] == 0:
s += str(polinom[0][1])
elif polinom[0][0] == 1:
s += 'x'
else:
s += 'x^' + str(polinom[0][0])
else:
if polinom[0][0] == 1:
s += str(polinom[0][1]) + 'x'
elif polinom[0][0] == 0:
s += str(polinom[0][1])
else:
s += str(polinom[0][1]) + 'x^' + str(polinom[0][0])
polinom.pop(0)
for el in polinom:
if el[1] == 0:
continue
elif el[1] < 0:
s += ' - '
el[1] = -el[1]
else:
s += ' + '
if el[1] == 1:
if el[0] == 0:
s += str(el[1])
elif el[0] == 1:
s += 'x'
else:
s += 'x^' + str(el[0])
else:
if el[0] == 1:
s += str(el[1]) + 'x'
elif el[0] == 0:
s += str(el[1])
else:
s += str(el[1]) + 'x^' + str(el[0])
print(s)
def input_data():
while True:
try:
n = int(input())
break
except:
print('enter an integer N')
continue
a = list()
i = 1
while n > i-1:
try:
tmp = list(map(int,(input()).split()))
if len(tmp) != 2:
print('enter two space separated integers')
continue
a.append(tmp)
i += 1
except:
print('enter two space separated integers')
return a
a = check_polinom(input_data())
b = check_polinom(input_data())
c = add_polinoms(a,b)
print_polinom(c)
It seems that you code does not clean up 0 coefficients. An additional phase should be added to your processing. Once you have the final coefficients of your polinomial, you should have two adjustments. You have already described one, that turns items with coefficient 1 from the form 1x to simply x. Another one is when you turn 0x to nothing. Then you only have to be careful to output something, so you should not turn every term into nothing. That is why there is a description to represent it as 0.
The easiset way to make this work would thus be:
Add a function to check if a polinomial has all zero coefficients: is_zero_polinom
Do something like this in print_polinom:
if is_zero_polinom(polinom):
print('0')
return
<here comes the current code>

How to check if consecutive digits in a number are even or odd?

I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:
def par_nepar(n):
cifre = []
while n != 0:
cifre.append(n % 10)
n //= 10
cifre = cifre[::-1]
ind = cifre[0]
for broj in cifre:
if cifre[0] % 2 == 0:
# for br in range(len(cifre)):
if cifre[ind + 1] % 2 != 0:
ind = cifre[ind+1]
n = int(input("Unesite broj n: "))
print(par_nepar(n))
As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].
Input examples:
>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False
try this:
def par_nepar(n):
split = [int(i) for i in str(n)].
for i in range(1,len(split)):
if (split[i] % 2 == 0) ^ (split[i-1] % 2 == 1):
return False
return True
Works as:
Converts integer to list: 1234 -> [1,2,3,4]
iterate the elements (excluding the first)
XOR condition that takes False if two consecutive digits are even or odd.
Tests:
>>> print(par_nepar(2749))
True
>>> print(par_nepar(2744))
False
mine solution is very simple. just change a bit your code and avoiding using indexes just looping through all digits in cifre and handling boolean flags:
def par_nepar(n):
cifre = []
while n != 0:
cifre.append(n % 10)
n //= 10
even = True
odd = True
output = "The number complies to the needed terms"
for broj in cifre:
if broj % 2 == 0 and odd:
even = True
odd = False
elif broj % 2 != 0 and even:
odd = True
even = False
else:
return "The number doesn't comply to the needed terms."
return output
n = int(input("Unesite broj n: "))
print(par_nepar(n))
outputs:
Unesite broj n: 33890
The number doesn't comply to the needed terms.
Unesite broj n: 4963850
The number complies to the needed terms
I think instead of getting an integer as input you can get a string and convert it to a list of integers
def par_nepar(n):
s,h=0,0
for i in range(len(n)-1):
if n[i]%2==0 and n[i+1]%2!=0:
s+=1
elif n[i]%2!=0 and n[i+1]%2==0:
h+=1
if s==len(n)//2 or h==len(n)//2:
print("The number complies to the needed terms")
else:
print("The number does not complies to the needed terms")
# list of digits in the provided input
n = list(map(lambda x: int(x),list(input("Unesite broj n: "))))
par_nepar(n)
def par_nepar(n):
cifre = list(str(n))
flg = False
if int(cifre[0]) % 2 == 0:
flg = True
for d in cifre[1:]:
_flg = False
if int(d) % 2 == 0:
_flg = True
if not flg^_flg:
print("The number does not complies to the needed terms")
return
flg = _flg
print("The number complies to the needed terms")
return
Maybe you would also like this one liner.
In a single loop, we find if the number mod 2 is the same as the (first number + the index) mod 2.
This works for you alternating use case.
par_nepar = lambda x: all([(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in enumerate(str(x))])
print(par_nepar(2749))
print(par_nepar(2744))
# Output
True
False
Or if you want with the strings you said, slightly bigger
par_nepar = lambda x: 'The number complies to the needed terms. ' if all(
[(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in
enumerate(str(x))]) else "The number doesn't comply to the needed terms."
#Output
The number complies to the needed terms.
The number doesn't comply to the needed terms.

How to detect if the middle digit of an integer is "0" without converting it into a string?

Trying to make a function which detects the the middle digit of an odd number is 0 and returns True if it is, otherwise False. I really want to get this function to work without converting the integer to a string first.
This is what I have so far:
def test(n):
n = str(n)
if len(n) % 2 == 0:
return False
else:
left_side = n[:len(n)//2]
right_side = n[(len(n)//2):]
if right_side[:1] == "0" and ((not "0" in left_side)and (not "0" in right_side[2:])):
return True
else:
return False
print (test(0)) # True
print (test(101)) # True
print (test(123)) # False
print (test(21031)) # True
n = 12345
digits = []
while n:
digit = n % 10
digits.append(digit)
n //= 10
digit_count = len(digits)
if digit_count % 2:
middle = digit_count // 2
print(digits[middle])
Output:
3
Alternatively, using math.log10:
from math import log10
n = 12345
digit_count = int(log10(n)) + 1
middle = digit_count // 2
print(n // 10 ** middle % 10)
See these two answers:
Length of an integer in Python
How to take the nth digit of a number in python
this should do it. it does convert it to a string, but honestly it's faster, easier, and just more efficient.
num = int(input("number too test: "))
def test(number):
num_len = len(str(number))
print(num_len)
if num_len % 2 == 0:
return False
else:
number = str(number)
half = int((num_len-1)/2)
print(number[half])
if int(number[half]) is 0:
return True
else:
return False
test(num)
Not that it will make much difference in terms of performance, but you can use the log function to compute the number of zeros in a number and remove the rightmost half by dividing to the correct power of 10. For example:
import math
def test(n):
if n == 0:
return True
digits = math.ceil(math.log(n + 1, 10)) - 1
return digits % 2 == 0 and not (n // 10**(digits / 2) % 10)

Odd digit count python

The task is to find the number of odd numbers in an integer.
count_odd_digits(n):
Given a non-negative integer, count how many digits of it are odd numbers.
example:
count_odd_digits(123450) → 3 #digits 1,3, and 5 are odd
I have so far:
def count_odd_digits(n):
ans = 0
for i in str(n):
if int(n) %2 == 1:
ans += 1
elif n[i]==0:
return None
But I am still failing my tests, what is going wrong in my code?
You have several problems:
elif n[i] == 0: return None is completely useless. You never want to return None; you just want to continue. Since all you are doing is continuing, it can just be removed.
if int(n) % 2 == 1 is testing the wrong thing. You want to check int(i), not int(n).
Change the code to this:
def count_odd_digits(n):
ans = 0
for i in str(n):
if int(i) % 2:
ans += 1
return ans
It would be easier to use a generator expression:
def count_odd_digits(n):
return sum(int(i) % 2 for i in str(n))
The return None part will immediatly terminate your function. Also you should convert i to an integer not the complete string.
A working function could look like this:
def count_odd_digits(n):
ans = 0
for i in str(n):
if int(i) %2 == 1:
ans += 1
# drop the elif part
# return after the for loop
return ans
count_odd_digits(123450)
Change int(n) to int(i)
def count_odd_digits(n):
ans = 0
for i in str(n):
if int(i) %2 == 1:
ans += 1
return ans
Another solution is to avoid converting to strings at all, and only use integers:
def count_odd_digits(n):
ans = 0
while n:
digit = n % 10
if digit % 2:
ans += 1
n //= 10
return ans

Using Python to convert integer to binary

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)

Categories