Skip to main content
 首页 » 编程设计

python之递归程序 : What am I doing wrong

2025年05月04日10itcoder

我正在尝试编写一个代码来分析一个单词是否是回文。 顺便说一句,回文是一个向后和向前读取相同的词。例如“女士”或“中午”

这是一个尝试:

x = raw_input("please enter a word:\n") 
L = len(x) 
 
 # this part returns the first letter of the word 
 
def first(word): 
    return word[0] 
 
# this part returns the last letter of the word 
 
def last(word): 
    return word[-1] 
 
 
def middle(word): 
    return word[1:-1] 
 
 
def is_palindrome(word): 
    if L <= 2: 
        print 'enter a word with at least three letters' 
    elif first(word) != last(word): 
        print 'This word is not a palindrome' 
    else: 
        word = middle(word) 
        is_palindrome(word) 
 
is_palindrome(x)  

但是当执行时,我得到了

IndexError: string index out of range 
...line 7, in first return word[0] 

“is_palindrome”的第一个分支运行完美。即当单词不是回文时,我不会出错。像“noopn”执行没有错误,但是错误在第二个分支

我已经玩过这段代码很多次了,但无法弄清楚“迭代部分”我有答案,但我还不想看。我需要弄清楚两件事: 1. 一种使函数 is_palindrome 中的迭代正常工作的方法? 2.最后退出程序的方法。

你们能告诉我如何在不提供解决方案的情况下回答这些问题吗?

最后我应该把打印语句放在哪里:print 'This word is a palindrome'

谢谢

请您参考如下方法:

要实现您的目标,为什么不直接使用:

string[::-1] == string 

而你回答的原因是当只有 1 个字母时,middle 将返回一个空字符串,然后 ''[0] 将导致错误。