因此,我的任务是查看并检查正整数(如果它是回文).我已正确完成所有操作,但在最后一步需要帮助.从用户给定的回文生成新回文的任务.我是否在while循环的正确轨道上,还是应该使用其他东西?因此结果是,如果您输入192,它将回馈产生回文.
483
867
1635
6996
"""Checks if the given, positive number, is in fact a palindrome"""
def palindrome(N):
x = list(str(N))
if (x[:] == x[::-1]):
return True
else: return False
"""Reverses the given positive integer"""
def reverse_int(N):
r = str(N)
x = r[::-1]
return int(x)
def palindrome_generator():
recieve = int(input("Enter a positive integer. "))
if (palindrome(recieve) == True):
print(recieve, " is a palindrome!")
else:
print("Generating a palindrome...")
while palindrome(recieve) == False:
reverse_int(recieve) + recieve
解决方法:
如果我正确地理解了您的任务,则应采取以下措施:
def reverse(num):
return num[::-1]
def is_pal(num):
return num == reverse(num)
inp = input("Enter a positive number:")
if is_pal(inp):
print("{} is a palindrome".format(inp))
else:
print("Generating...")
while not is_pal(inp):
inp = str(int(inp) + int(reverse(inp)))
print(inp)
变量inp始终是字符串,并且仅将其转换为int以进行算术运算.