I am writing a binary addition program but am unsure as to why when the inputs start with a zero the output is incorect.The output is also incorrect when the program has to add zeros to the start of one of the inputs to make them the same length.
a = input('Enter first binary number\t')
b = input('Enter second binary number\t')
carry = 0
answer = ""
length = (max(len(a),len(b))) - min(len(a),len(b))
if b > a:
a = length * '0' + a
elif a > b:
b = length * '0' + b
print(a)
print(b)
for i in range(len(a)-1, -1, -1):
x = carry
if a[i] == '1': x += 1
else: x = 0
if b[i] == '1': x += 1
else: x = 0
if x % 2 == 1: answer = '1' + answer
else: answer = '0' + answer
if x < 2: carry = 0
else: carry = 1
if carry == 1: answer = '1' + answer
print(answer)
What an excellent opportunity to explore some Boolean Logic.
Adding binary like this can be done with two "half adders" and an "or"
First of all the "Half Adder" which is a XOR to give you a summed output and an AND to give you a carry.
[EDIT as per comments: python does have an XOR implemented as ^ but not as a "word" like and not or. I am leaving the answer as is, due to the fact it is explaining the Boolean logic behind a binary add]
As python doesn't come with a XOR, we will have to code one.
XOR itself is two AND's (with reversed inputs) and an OR, as demonstrated by this:
This would result is a simple function, like this:
def xor(bit_a, bit_b):
A1 = bit_a and (not bit_b)
A2 = (not bit_a) and bit_b
return int(A1 or A2)
Others may want to write this as follows:
def xor(bit_a, bit_b):
return int(bit_a != bit_b)
which is very valid, but I am using the Boolean example here.
Then we code the "Half Adder" which has 2 inputs (bit_a, bit_b) and gives two outputs the XOR for sum and the AND for carry:
def half_adder(bit_a, bit_b):
return (xor(bit_a, bit_b), bit_a and bit_b)
so two "Half Adders" and an "OR" will make a "Full Adder" like this:
As you can see, it will have 3 inputs (bit_a, bit_b, carry) and two outputs (sum and carry). This will look like this in python:
def full_adder(bit_a, bit_b, carry=0):
sum1, carry1 = half_adder(bit_a, bit_b)
sum2, carry2 = half_adder(sum1, carry)
return (sum2, carry1 or carry2)
If you like to look at the Full Adder as one logic diagram, it would look like this:
Then we need to call this full adder, starting at the Least Significant Bit (LSB), with 0 as carry, and work our way to the Most Significant Bit (MSB) where we carry the carry as input to the next step, as indicated here for 4 bits:
This will result is something like this:
def binary_string_adder(bits_a, bits_b):
carry = 0
result = ''
for i in range(len(bits_a)-1 , -1, -1):
summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry)
result += str(summ)
result += str(carry)
return result[::-1]
As you see we need to reverse the result string, as we built it up "the wrong way".
Putting it all together as full working code:
# boolean binary string adder
def rjust_lenght(s1, s2, fill='0'):
l1, l2 = len(s1), len(s2)
if l1 > l2:
s2 = s2.rjust(l1, fill)
elif l2 > l1:
s1 = s1.rjust(l2, fill)
return (s1, s2)
def get_input():
bits_a = input('input your first binary string ')
bits_b = input('input your second binary string ')
return rjust_lenght(bits_a, bits_b)
def xor(bit_a, bit_b):
A1 = bit_a and (not bit_b)
A2 = (not bit_a) and bit_b
return int(A1 or A2)
def half_adder(bit_a, bit_b):
return (xor(bit_a, bit_b), bit_a and bit_b)
def full_adder(bit_a, bit_b, carry=0):
sum1, carry1 = half_adder(bit_a, bit_b)
sum2, carry2 = half_adder(sum1, carry)
return (sum2, carry1 or carry2)
def binary_string_adder(bits_a, bits_b):
carry = 0
result = ''
for i in range(len(bits_a)-1 , -1, -1):
summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry)
result += str(summ)
result += str(carry)
return result[::-1]
def main():
bits_a, bits_b = get_input()
print('1st string of bits is : {}, ({})'.format(bits_a, int(bits_a, 2)))
print('2nd string of bits is : {}, ({})'.format(bits_b, int(bits_b, 2)))
result = binary_string_adder(bits_a, bits_b)
print('summarized is : {}, ({})'.format(result, int(result, 2)))
if __name__ == '__main__':
main()
two internet sources used for the pictures:
https://www.electronics-tutorials.ws/combination/comb_7.html
https://www.allaboutcircuits.com/textbook/digital/chpt-7/the-exclusive-or-function-xor/
For fun, you can do this in three lines, of which two is actually getting the input:
bits_a = input('input your first binary string ')
bits_b = input('input your second binary string ')
print('{0:b}'.format(int(bits_a, 2) + int(bits_b, 2)))
And in your own code, you are throwing away a carry if on second/subsequent iteration one of the bits are 0, then you set x = 0 which contains the carry of the previous itteration.
this is how i managed to complete this, hope you find this useful.
#Binary multiplication program.
def binaryAddition(bin0, bin1):
c = 0
answer = ''
if len(bin0) > len(bin1):
bin1 = (len(bin0) - len(bin1))*"0" + bin1
elif len(bin1) > len(bin0):
bin0 = (len(bin1) - len(bin0))*"0" + bin0
#Goes through the binary strings and tells the computer what the anser should be.
for i in range(len(bin0)-1,-1,-1):
j = bin0[i]
k = bin1[i]
j, k = int(j), int(k)
if k + j + c == 0:
c = 0
answer = '0' + answer
elif k + j + c == 1:
c = 0
answer = '1' + answer
elif k + j + c == 2:
c = 1
answer = '0' + answer
elif k + j + c == 3:
c = 1
answer = '1' + answer
else:
print("There is something wrong. Make sure all the numbers are a '1' or a '0'. Try again.") #One of the numbers is not a 1 or a 0.
main()
return answer
def binaryMultiplication(bin0,bin1):
answer = '0'*8
if len(bin0) > len(bin1):
bin1 = (len(bin0) - len(bin1))*"0" + bin1
elif len(bin1) > len(bin0):
bin0 = (len(bin1) - len(bin0))*"0" + bin0
for i in range(len(bin0)-1,-1,-1):
if bin1[i] == '0':
num = '0'*len(answer)
elif bin1[i] == '1':
num = bin0 + '0'*((len(bin0)-1)-i)
answer = binaryAddition(num, answer)
print(answer)
def main():
try:
bin0, bin1 = input("Input both binary inputs separated by a space.\n").split(" ")
except:
print("Something went wrong. Perhaps there was not a space between you numbers.")
main()
binaryMultiplication(bin0,bin1)
choice = input("Do you want to go again?y/n\n").upper()
if choice == 'Y':
main()
else: input()
main()
The following adds integers i1 and i2 using bitwise logical operators (i1 and i2 are overwritten). It computes the bitwise sum by i1 xor i2 and the carry bit by (i1 & i2)<<1. It iterates until the shift register is empty. In general this will be a lot faster than bit-by-bit
while i2: # check shift register != 0
i1, i2 = i1^i2, (i1&i2) << 1 # update registers
Related
I have one code here
and need to change the order of the digits
import math
def sucet_cisel(number):
bla: int = 0
while number > 0:
xyzpremenna = number % 10
bla += xyzpremenna
number = (number - xyzpremenna) / 10
return bla
def digit_root(n):
if n == 0: return 0
return (n - 1) % 9 + 1
if __name__ == '__main__':
n = int(input("od čisla:"))
m = int(input("do čisla:"))
for i in range(1,m + 1):
sucet: int = math.floor(sucet_cisel(n*i))
t=(n*i)*(2)
x=' ';
print(n,"*",i,"=",n*i,(x*4),"*2","=",t,sep='')
they need to add () to this code so that in each result where there are 4 numbers they are moved
therefore print (t) need this script to run at that number
t=(ni)(2)
and the result of this to turn into this code
val = list(str(i))
digit = val.pop(-3)
new = int(''.join(val+[digit]))
od čisla:2554
do čisla:4505
2554*4505=11505770 *2=23011540
23011540
23011405
the script stops at the number I enter where is the problem?
20*1=20 *2=40
20*2=40 *2=80
20*3=60 *2=120
20*4=80 *2=160
20*5=100 *2=200
20*6=120 *2=240
20*7=140 *2=280
20*8=160 *2=320
20*9=180 *2=360
20*10=200 *2=400
20*11=220 *2=440
20*12=240 *2=480
20*13=260 *2=520
20*14=280 *2=560
20*15=300 *2=600
20*16=320 *2=640
20*17=340 *2=680
20*18=360 *2=720
20*19=380 *2=760
20*20=400 *2=800
this makes a code if I give
n = int (input ("from number:"))
m = int (input ("to number:"))
n20
m20
however, if in this script there is i
val = list (page (s))
digit = val.pop (-3)
new = int (''. join (val + [digit]))
does it calculate only one result where is the error?
Very similar to the answer from Tim Roberts, but using slices and format strings.
n = 12345678
s = str(n)
x = int(f"{s[:-5]}{s[::-1][:4]}")
s is '12345678', s[:-5] is '1234', s[::-1] is '87654321', and s[::-1][:4] is '8765'. Put it all together and x is 12348765.
OK, let's rewrite your problem to "given a number of greater than 4 digits, I want that same number but with all permutations of the last 4 digits.
import itertools
def permute(number):
val = str(number)
prefix = val[:-4]
for combo in itertools.permutations(val[-4:]):
yield int(prefix+''.join(combo))
print(list(permute(12345678)))
I apologies if this question has already been answered but I search for this and couldn't find the answer for it. maybe I am writing the question in a weird way but I'm new so I'm sorry about that.
there are many problems with my code and I think its very inefficient because if the input of a + b for example was -25 + 2 then a will only read operation[1] which will be 2, and when I run it, it will not give me the answer I want.
To cut a long story short, is there a way to enter a line of code that combines all numbers before the sign?
for example a = all the numbers before (-) and b = all numbers after the sign (-).
this is a sample of the code I'm trying to write:
operation = input('Enter an arithemtic operation: ')
print(operation)
operation = operation.replace(" ", "")
if len(operation) == 3:
a = int(operation[0])
b = int(operation[2])
sign2 = operation[1]
if(sign2 == '+'):
sum = a + b
print(sum)
elif(sign2 == '-'):
sum = a - b
print(sum)
elif(sign2 == '*'):
sum = a * b
print(sum)
elif(sign2 == '/'):
sum = a / b
print(round(sum, 3))
elif len(operation) == 4:
a = int(operation[1]) * -1
b = int(operation[3])
sign1 = operation[0]
sign2 = operation[2]
if(sign2 == '+'):
sum = a + b
print(sum)
elif(sign2 == '-'):
sum = a - b
print(sum)
elif(sign2 == '*'):
sum = a * b
print(sum)
elif(sign2 == '/'):
sum = a / b
print(round(sum, 3))
else:
print('input invalid')
Sorry if this is wrong, because maybe I'm not understanding the question right, but can't you just use eval to get the value of the arithmetic operation?
example_input = "1 + 2 * 3"
print(eval(example_input))
## OUTPUT:
# 7
This will work as long as the expression entered in the example_input is a valid python expression.
You could use regular expression (Regex) from the re library, it is a little complex but if you learn the basics it will help you a lot. Check my suggestion below
import re
def foo():
operation = input("Enter Operation: ")
match = re.findall(r"([+-]\d+)\b\s*([+-])\s*(\d+)", operation) # This line finds the three components of the equation/operation (LHS, sign & RHS) and excludes any spaces in-between
lft = int(match[0][0])
rght = int(match[0][-1])
sign = match[0][1]
if sign == "+":
return lft + rght
elif sign == "-":
return lft - rght
else:
return False
Generally you should find a lot of help for regex related stuff, but it is worth learning a little about it. Sentdex has a really nice tutorial about this.
I am trying to integrate a polynomial function via the Trapezoidal Method (I can change to a more accurate method later). My code isn't perfect, and I'd like to understand exactly why it doesn't work. One problem I have is that the while loop does not end. My code thus far is as follows.
def Integrate_Trapezoidal(x_LoBound,x_HiBound,N):
"""
INPUT :
x_LoBound -- lower bound of integral
x_HiBound -- upper bound of integral
N -- number of slices (N --> inf ==> integral)
OUTPUT :
-- approximate value of integral
"""
## CREATE ALPHABET
alphabet = [chr(i) for i in range(ord('a'),ord('z')+1)]
## alphabet = ['a','b','c',...,'z'] ##
## WOULD LOVE TO TRY FLOATING INPUTS VIA ARRAY COMPREHENSION
a = float(input("What is the coefficient of the lowest order term: "))
CoeffList = []
CoeffNumList = []
LengthCoeffList = [] ## [1,2,3,...,max] where max = coefficient of highest-order term
for letter in alphabet:
AddOne = int(1)
AddOne += int(1)
for i in range(int(1),int(AddOne)):
letter = alphabet[int(i)]
while letter in alphabet:
CoeffList.append(letter)
LengthCoeffList.append(len(CoeffList))
# alphabet[i]
# i = i + 1
letter = float(input("What is the coefficient of the next-order term: ")) ## GO FROM a = ___ TO b = ___ TO c = ___ ...
CoeffNumList.append(letter)
if float(input("What is the coefficient of the next-order term: ")) == '0':
print("Type 'Y for YES and 'N' for NO")
YESorNO = str(input("Is that the last term of the polynomial: "))
endterm = YESorNO[-1] ## look at last character of string
if endterm == 'N' or endterm == 'n' or endterm == 'no' or endterm == 'NO' or endterm == 'No':
pass
elif endterm == 'Y' or endterm == 'y' or endterm == 'YES' or endterm == 'yes' or endterm == 'Yes':
break
def f(x):
"""
INPUT :
x -- variable of function
EX: x = x_LoBound OR x = x_HiBound
OUTPUT :
function -- f(x) = a x^0 + b x^1 + ...
EX: f(x_LoBound) OR f(x_HiBound)
"""
for expval in LengthCoeffList and CoeffNum in CoeffNumList:
# function = 0
function += CoeffNum * x**expval
return function
letter = alphabet[int(i+1)] ## GO FROM a TO b TO c ...
## TRAPEZOIDAL RULE
# def f(x):
# return x**4 - 2*x + 1
ht = (x_HiBound - x_LoBound) / N
ss = 0.5 * f(x_LoBound) + 0.5 * f(x_HiBound)
for num in range(1,N):
ss += f(x_LoBound + num*ht)
return ht*ss
checkanswer = Integrate_Trapezoidal(0,2,10)
print(checkanswer)
I've had a go at looking over your code and found something that I think works, checking against a couple of college handouts I downloaded. As you have said in the comments, there were a lot of extra lists which aren't necessary, so I've cut back the code a lot there.
In particular, if the presumption if that each coefficient is added in sequence from lowest to highest order, and 0 is added for any that aren't there, all you need is the number of the element in the list to know the power of x.
I also moved the definition of f() to create the helper function solve_point() which works the same I think. In particular, sum and enumerate are built in, with enumerate iterating through coeff_list and also returning a count to give the power (0 upwards).
get_coefficients() was from your old Integrate_Trapezoidal() but more focused on just one thing - which is why it then returns CoeffList to be finally processed at the end.
def solve_point(x, coeff_list):
return sum(coeff * x**e for e, coeff in enumerate(coeff_list))
def get_coefficients():
CoeffList = []
while True:
# GO FROM a = ___ TO b = ___ TO c = ___ ...
coeff = float(input("What is the coefficient of the next-order term: "))
CoeffList.append(coeff)
if coeff == 0:
YESorNO = raw_input("Is that the last term of the polynomial: [Y/N] ")
if YESorNO.upper() == 'Y':
return CoeffList[:-1]
lo, hi, n = 0, 2, 6
coeff_list = get_coefficients()
ht = (hi - lo) / float(n)
ss = 0.5 * solve_point(lo, coeff_list) + 0.5 * solve_point(hi, coeff_list)
for num in range(1,n):
ss += solve_point(lo + num*ht, coeff_list)
checkanswer = ht*ss
print(checkanswer)
I think its right - I have done a couple of checks. Hopefully it may be of help for your rewrite! If you have any examples that don't work, it would be good to know, or any errors you can see...
I'm trying to make a python program which takes in a user equation, for example: "168/24+8=11*3-16", and tries to make both sides of the equation equal to each other by removing any 2 characters from the user input. This is what I have so far:
def compute(side):
val = int(side[0])
x= val
y=0
z=None
for i in range(1, len(side)-1):
if side[i].isdigit():
x= (x*10)+ int(side[i])
if x == side[i].isdigit():
x= int(side[i])
else:
op = side[i]
if op=="+":
val += x
elif op == "-":
val -= x
elif op == "*":
val *= x
else:
val /= x
return print(val)
I have edited my compute function.
def evaluate(e):
side1 = ""
side2 = ""
equalsign = e.index("=")
side1= e[:equalsign - 1]
side2= e[:equalsign + 1]
if compute (side1) == compute(side2):
return True
else:
return False
def solve():
# use a for loop with in a for loop to compare all possible pairs
pass
def main():
e= input("Enter an equation: ")
evaluate(e)
main()
For the actual solve function I want to test all possible pairs for each side of the equation and with every pair removed check if the equation is equal to the other side. I was thinking of using a for loop that said:
for i in side1:
j= [:x]+[x+1:y]+[y+1:]
if compute(j)==compute(side2):
val= compute(j)
return val
How should I go about doing this? I'm getting a little confused on how to really approach this program.
Let's get to the preliminary issues.
e = raw_input("Enter an equation: ") # input is fine if you are using Python3.x
side1 = e[:equalsign] #note that a[start:end] does not include a[end]
side2 = e[equalsign + 1:] # not e[:equalsign + 1].
val = int(side[0]) # not val = side[0] which will make val a string
In the operations part, you are doing val += side # or -= / *= / /= .. remember side is a string
Edits:
Yeah, I'm still stuck up with Python 2.7 (use input if Python 3)
To solve for the value of each side, you could simply use eval(side1) # or eval(side2). There could be alternatives to using eval. (I am a novice myself). eval will also take care of PEMDAS.
Added edit to side1 expression.
Updated with code written so far.
def compute(side):
return eval(side)
def evaluate(e):
side1, side2 = e.split('=')
if compute(side1) == compute(side2):
return (True, e)
else:
return (False, 'Not Possible')
def solve(e):
for i in range(len(e)): # loop through user input
if e[i] in '=': # you dont want to remove the equal sign
continue
for j in range(i+1, len(e)): # loop from the next index, you dont want
if e[j] in '=': # to remove the same char
continue # you dont want to remove '=' or operators
new_exp = e[:i] + e[i+1:j] + e[j+1:] # e[i] and e[j] are the removed chars
#print e[i], e[j], new_exp # this is the new expression
s1, s2 = new_exp.split('=')
try:
if compute(s1) == compute(s2):
return (True, new_exp)
except:
continue
return (False, 'not possible')
def main():
e= raw_input("Enter an equation: ")
print evaluate(e.replace(' ', ''))
main()
This is what I have come up with so far (works for your example at least).
It assumes that operators are not to be removed
Final edit: Updated code taking into account #Chronical 's suggestions
Removed the try-except block in each loop and instead just use it after calculating each side
Here is code that does exactly what you want:
from itertools import combinations
def calc(term):
try:
return eval(term)
except SyntaxError:
return None
def check(e):
sides = e.split("=")
if len(sides) != 2:
return False
return calc(sides[0]) == calc(sides[1])
equation = "168/24+8 = 11*3-16".replace(" ", "")
for (a, b) in combinations(range(len(equation)), 2):
equ = equation[:a] + equation[a+1:b] + equation[b+1:]
if check(equ):
print equ
Core tricks:
use eval() for evaluation. If you use this for anything, please be aware of the security implications of this trick.
use itertools.combinations to create all possible pairs of characters to remove
Do not try to handle = too specially – just catch it in check()
I'm creating a python script which prints out the whole song of '99 bottles of beer', but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.
This is my full script,
def reverse(str):
return str[::-1]
def plural(word, b):
if b != 1:
return word + 's'
else:
return word
def line(b, ending):
print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)
for i in range(99, 0, -1):
line(i, "of beer on the wall")
line(i, "of beer"
print reverse("Take one down, pass it around")
line(i-1, "of beer on the wall \n")
I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.
Without converting the number to a string:
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?
def line(bottles, ending):
return "{0} {1} {2}".format(bottles,
plural("bottle", bottles),
ending)
Which runs like:
>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'
Then pass the result to reverse:
>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'
This makes it much easier to test each part of the code separately and see what's going on when you put it all together.
Something like this?
>>> x = 123
>>> str(x)
'123'
>>> str(x)[::-1]
'321'
best way is
x=12345
a=str(x)[::-1]\\ In this process i have create string of inverse of integer (a="54321")
a=int(a) \\ Here i have converted string a in integer
or
one line code is
a=int(str(x)[::-1]))
def reverse(x):
re = 0
negative = x < 0
MAX_BIG = 2 ** 31 -1
MIN_BIG = -2 ** 31
x = abs(x)
while x != 0:
a = int(x % 10)
re = re * 10 + a
x = int(x // 10)
reverse = -1 * re if negative else re
return 0 if reverse < MIN_BIG or reverse > MAX_BIG else reverse
this is for 32 - bit integer ( -2^31 ; 2^31-1 )
def reverse_number(n):
r = 0
while n > 0:
r = (r*10) + (n % 10)
print(r)
r *=10
n //= 10
return r
print(reverse_number(123))
You can cast an integer to string with str(i) and then use your reverse function.
The following line should do what you are looking for:
def line(b, ending):
print reverse(str(b)) or reverse('No more'), plural(reverse('bottle'),reverse(str(b))), reverse(ending)
Original number is taken in a
a = 123
We convert the int to string ,then reverse it and again convert in int and store reversed number in b
b = int("".join(reversed(str(a))))
Print the values of a and b
print(a,b)
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
This code will not work if the number ends with zeros, example 100 and 1000 return 1
def reverse(num):
rev = 0
while(num != 0):
reminder = num % 10
rev = (rev * 10 ) + reminder
num = num // 10
print ("Reverse number is : " , rev )
num=input("enter number : ")
reverse(int(num))
#/ always results into float
#// division that results into whole number adjusted to the left in the number line
I think the following code should be good to reverse your positive integer.
You can use it as a function in your code.
n = input() # input is always taken as a string
rev = int(str(n)[::-1])
If you are having n as integer then you need to specify it as str here as shown. This is the quickest way to reverse a positive integer
import math
def Function(inputt):
a = 1
input2 = inputt
while(input2 > 9):
input2 = input2/10
a = a + 1
print("There are ", a, " numbers ")
N = 10
m = 1
print(" THe reverse numbers are: ")
for i in range(a):
l = (inputt%N)/m
print(math.floor(l), end = '')
N = N*10
m = m*10
print(" \n")
return 0
enter = int(input("Enter the number: "))
print(Function(enter))
More robust solution to handle negative numbers:
def reverse_integer(num):
sign = [1,-1][num < 0]
output = sign * int(str(abs(num))[::-1])
An easy and fast way to do it is as follows:
def reverse(x: int|str) -> int:
reverse_x = int(''.join([dgt for dgt in reversed(num:=str(x)) if dgt != '-']))
if '-' in num:
reverse_x = -reverse_x'
return reverse_x
First we create a list (using list comprehension) of the digits in reverse order. However, we must exclude the sign (otherwise the number would turn out like [3, 2, 1, -]). We now turn the list into a string using the ''.join() method.
Next we check if the original number had a negative sign in it. If it did, we would add a negative sign to reverse_x.
Easily you can write this class:
class reverse_number:
def __init__(self,rvs_num):
self.rvs_num = rvs_num
rvs_ed = int(str(rvs_num)[::-1])
print(rvs_ed)
You can use it by writing:
reverse_number(your number)
I have written it in a different way, but it works
def isPalindrome(x: int) -> bool:
if x<0:
return False
elif x<10:
return True
else:
rev=0
rem = x%10
quot = x//10
rev = rev*10+rem
while (quot>=10):
rem = quot%10
quot = quot//10
rev = rev*10+rem
rev = rev*10+quot
if rev==x:
return True
else:
return False
res=isPalindrome(1221)