You need to enable JavaScript to run this app. Python递归实现回文校验的代码异常排查
优惠活动
大模型
产品
解决方案
定价
更多

Python递归实现回文校验的代码异常排查

现有代码运行异常排查

异常1:非回文输入时无法正确输出反转字符串

  • 问题根源出在else分支的变量引用错误:代码中引用的new_word是palindrome函数初始化的空字符串,而非reverse函数计算返回的实际反转结果result。
  • Python的字符串是不可变类型,递归过程中每一层对字符串的拼接都会生成全新的字符串对象,外层初始化的new_word从创建后就不会被递归逻辑修改,永远保持空值。这就导致非回文场景下,打印内容永远是Sorry, is NOT a palindrome,完全无法展示反转后的正确内容。

异常2:回文输入时无对应打印输出

  • 这类空输出基本由缩进错位导致:回文判断分支的print语句如果没有和同层级的逻辑代码保持对齐,会被Python解释器识别为其他代码块的组成部分,导致判断为回文时根本执行不到对应的打印语句。
修复实现

最小改动版(保留原有代码结构)

仅修正变量引用错误、统一代码缩进,不调整原有递归逻辑框架:

def reverse(choice, index, new_word):
    if index < 0:
        return new_word
    new_word += choice[index]
    return reverse(choice, index - 1, new_word)

def palindrome():
    new_word = ""
    choice = input("Please enter a word to check if it is palindrome:")
    result = reverse(choice, len(choice) - 1, new_word)

    if result == choice:
        print("That word", choice, "IS a palindrome")
    else:
        # 替换原代码中引用的空值变量为递归返回的实际反转结果
        print("Sorry, the reverse of", choice, "is", result, ", it is NOT a palindrome")

palindrome()

优化版(减少出错可能的递归写法)

去掉冗余的索引参数、初始拼接值的传递,从根源上避免变量作用域错配的问题,利用Python字符串切片简化递归逻辑:

def reverse(s):
    # 递归终止边界:字符串长度≤1时,本身就是反转结果
    if len(s) <= 1:
        return s
    # 递归逻辑:将去掉首字符的剩余字符串递归反转后,把首字符追加到结果末尾
    return reverse(s[1:]) + s[0]

def palindrome():
    # 去除输入附带的前后多余空格,避免不可见字符导致判断错误
    choice = input("Please enter a word to check if it is palindrome:").strip()
    reversed_str = reverse(choice)

    if reversed_str == choice:
        print(f"That word '{choice}' IS a palindrome")
    else:
        print(f"Sorry, the reverse of '{choice}' is '{reversed_str}', it is NOT a palindrome")

palindrome()

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 13:06:11