谁能告诉我这段代码有什么问题?

时间:2017-10-24 16:29:16

标签: python-3.x

我是python编程新手并试图解决Spoj挑战 我试图编码Palindrome数字。我的代码:

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)时,系列应该会中断 然而它继续无限循环。 如果您愿意,也可以给代码提供一些建议

1 个答案:

答案 0 :(得分:0)

不需要递归。这可以通过简单的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 palindrome