我是python编程的新手,为了解决Spoj挑战,我尝试对回文数字进行编码。我的代码:
num = int(input("Enter a number"))
def test_num(number):
num_list = list(str(number))
elements = []
for j in range(len(num_list)):
elements.insert(0, num_list[j])
result = ''.join(str(e) for e in elements)
if result == number:
print(num)
else:
print("Unmatched", number, result)
test_num((number + 1))
test_num(num)如果我输入,num =9,我的输出变成无限循环。显然,if语句并不是真的。
Enter a number9
Unmatched 9 9
Unmatched 10 01
Unmatched 11 11 # This is where it is supposed to break
Unmatched 12 21
Unmatched 13 31
Unmatched 14 41
Unmatched 15 51
Unmatched 16 61
Unmatched 17 71当结果== num (或者在这个例子中是11 )时,系列被认为是中断的,但它仍然继续无限循环。如果您愿意,还可以为代码提供一些建议
发布于 2017-10-25 01:00:56
不需要递归。这可以通过一个简单的while循环来解决。下面的代码可以工作
num = int(input("Enter a number "))
def next_palindrome(number):
new_number = number+1
while True:
string = str(new_number)
if string == ''.join(string[::-1]):
return new_number
else:
print('{} not a palindrome'.format(new_number))
new_number += 1
print('{} is a palindrome'.format(next_palindrome(num)))例如input = 15,您将获得以下输出
Enter a number 15
16 is not a palindrome
17 is not a palindrome
18 is not a palindrome
19 is not a palindrome
20 is not a palindrome
21 is not a palindrome
22 is a palindromehttps://stackoverflow.com/questions/46915610
复制相似问题