There was a question which asked to write a code, to get continuous integer input from user until a negative integer is input and for each input I should evaluate if it is a palindrome in both base 10 and 2. If yes then print 'Yes' else print 'No'.
For example: 99 = (1100011)base2, both versions are palindrome so it prints 'Yes'
This is a usual elementary method.
while 1:
num = int(input('Input: '))
if num > 0:
num1 = str(num)
if num1 == num1[::-1]:
list1 = list(bin(num))
list1.pop(0)
list1.pop(0)
n = ''.join(list1)
if n == n[::-1]:
print('Yes')
else:
print('No')
else:
print('No')
else:
break
But when I tried to type a code using defining a new function it didn't work well. Here following is the code. Can you note what is wrong with this.
def palindrome(n):
n = str(n)
if n == n[::-1]:
return True
else:
return False
def b2_palindrome(n):
list1 = list(bin(n))
list1.pop(0)
list1.pop(0)
n = ''.join(list1)
palindrome(n)
while 1:
num = int(input('Input: '))
if num > 0:
if b2_palindrome(num) and palindrome(num):
print('Yes')
else:
print('No')
else:
break
@dspencer: edited the indentations
you're not returning the value of the palindrome
call in b2_palindrome
see below:
def b2_palindrome(n):
list1 = list(bin(n))
list1.pop(0)
list1.pop(0)
n = ''.join(list1)
return palindrome(n) # <-- added return here