【问题标题】:Palindrome using recursion [closed]使用递归的回文[关闭]
【发布时间】:2021-12-04 10:49:48
【问题描述】:

请帮助我在 Python 中正确编码。

T = int(input("Number of test cases: "))    
for i in range(T+1):
    
    def checkPalindrome(str):
            l=len(str)
        
            if l==0 or l==1:
                return "It is a palindrome"
            
            if str[0]!=str[-1]:
                return "It is not a palindrome"
            
            else:
                str_new= str[1::-1]
            
                output= checkPalindrome(str_new)
                return output
            
            
            
            
str= [input(). split() for i in range(T) ]
checkPalindrome(str)

它不工作。

【问题讨论】:

  • 编辑问题以解释“它不起作用”。究竟会发生什么,应该发生什么?
  • 你不需要定义函数T不同的时间。您还将整个测试用例 列表 一次传递给 checkPalindrome,而不是分别在每个测试用例上调用 checkPalindrome
  • 您通常不想在 Python 中将变量命名为 strstr 是一个内置函数名,用于将变量转换为string 对象。

标签: python python-3.x list python-2.7 python-requests


【解决方案1】:

例如:

def checkPalindrome(word):
    l = len(word)
    if l == 0 or l == 1:
        return "It is a palindrome"        
    if word[0] != word[-1]:
        return "It is not a palindrome"
    return checkPalindrome(word[1:-1])
            
t = int(input("Number of test cases: "))

for i in range(t):
    print(checkPalindrome(input()))

【讨论】:

    【解决方案2】:

    下一次递归调用的更新字符串不正确。切片格式遵循[start:end:step]。所以str[1::-1] 暗示从索引一开始并向后退一步(用-1 表示)。
    新字符串必须从索引一开始到结束,不包括最后一个字符。可以这样完成。

    str_new = str[1:-1]
    

    【讨论】:

      猜你喜欢
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      相关资源
      最近更新 更多