回文递归
Recursion with palindromes
我有一个 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)))
实现 check_palindrome
递归版本的一种方法是用对 check_palindrome
的调用替换 for
循环。然而,为了避免无限循环,您需要从列表中删除一个值并对其进行处理,从而在每次递归调用时将 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)
我有一个 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)))
实现 check_palindrome
递归版本的一种方法是用对 check_palindrome
的调用替换 for
循环。然而,为了避免无限循环,您需要从列表中删除一个值并对其进行处理,从而在每次递归调用时将 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)