我用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!*
限制:
我已经编写了下面的代码,它工作得非常好,但是在第二个定义的函数中,我没有使用递归,因为我不知道如何处理语句的这一部分。 如果有人能帮助我,我将非常感激
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)))
实现
check_palindrome
递归版本的一种方法是将for
循环替换为对check_palindrome
的调用。但是,为了避免无限循环,您需要从列表中删除一个值并对其进行处理,从而在每次递归调用时将subsetsList
缩小1。最后,您需要检查subsetsList
何时变为空,并在此时退出递归例如:
相关问题 更多 >
编程相关推荐