带回文的递归

2024-10-02 16:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了一个递归语句

声明

回文

A palindrome is a word which reads the same backwards as forwards (madam, noon, radar…). Write a program which reads a string and prints all palindromes, which can be obtained by removing of some characters of the string. The resulting palindromes do not need to be English words!*

限制:

  • 不要打印长度为1的回文(一个字母的回文)
  • 每个回文只打印一次

我已经编写了下面的代码,它工作得非常好,但是在第二个定义的函数中,我没有使用递归,因为我不知道如何处理语句的这一部分。 如果有人能帮助我,我将非常感激

def find_subsets(seq, n):
    if n != 0:
        result = []
        subsets = find_subsets(seq, n-1)
        for subset in subsets:
            result += [subset]
            result += [[seq[n-1]] + subset]
        return result
    else:
        return [[]]
def check_palindrome(subsetsList):
    finalList = []
    for x in subsetsList:
        if x[::-1] == x and len(x)>1:
            string = " ".join(x)
            print(string)
        else:
           continue
word = input("Write string: ")
check_palindrome(find_subsets(word, len(word)))

Tags: andthewhichstring语句resultfindseq
1条回答
网友
1楼 · 发布于 2024-10-02 16:28:36

实现check_palindrome递归版本的一种方法是将for循环替换为对check_palindrome的调用。但是,为了避免无限循环,您需要从列表中删除一个值并对其进行处理,从而在每次递归调用时将subsetsList缩小1。最后,您需要检查subsetsList何时变为空,并在此时退出递归

例如:

def check_palindrome(subsetsList):
    if not subsetsList:
        return
    
    x = subsetsList.pop()
    if x[::-1] == x and len(x)>1:
        string = " ".join(x)
        print(string)
    
    check_palindrome(subsetsList)

相关问题 更多 >