[英]Problem in coding with function in python: Base 2 & 10 integer palindrome
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'.有一个问题要求编写代码,从用户获取连续整数输入,直到输入负整数,对于每个输入,我应该评估它是否是基数为 10 和 2 的回文。如果是,则打印“是”否则打印“否”。
For example: 99 = (1100011)base2, both versions are palindrome so it prints 'Yes'例如:99 = (1100011)base2,两个版本都是回文,所以打印“是”
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 @dspencer:编辑缩进
you're not returning the value of the palindrome
call in b2_palindrome
你没有在
b2_palindrome
返回palindrome
调用的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.