python - 递归检查字母是否在给定字符串中

标签 python recursion

我想使用递归检查一个字母是否在字符串中。我解决这个问题的方法是使用 set 和子集来获得我想要的输出,但这不是递归的。我将如何编写递归方法?这是我到目前为止所做的:

import sys


userInput = str(sys.argv[1])
letters = ["e", "f"]

if set(letters).issubset(userInput):
    print(userInput +" exist in these 2 letters!)
else:
    print(userInput + " does not exist in these 2 letters!")

给定字符串示例:wife

最佳答案

我认为你的解决方案很好,但如果你真的想要一个递归函数,那么下面的函数格式是函数式编程的典型格式:

def check_letters(compare_to, lst):
    if len(lst) == 0:
        return True
    else:
        if lst[0] in compare_to:
            return check_letters(compare_to, lst[1:]) # recursive step
        else:
            return False

if check_letters(userInput, letters):
    ...

所以我们的想法是检查列表的“头部”(第 0 个元素),如果它满足您的谓词,则继续递归到列表的“尾部”。

因此每个递归步骤都会检查列表中的第一个元素,然后将列表的其余部分“向下”递归。这里我用slicing :

l = [1,2,3]
print(l[1:]) # create a new list from index 1
# Outputs: [2,3]

由于 python 是零索引的,因此 1 表示第二个元素。

@cdlane 所指出的那样支持重复的字母,递归可以传递输入并替换出现:

return check_letters(compare_to.replace(lst[0], "", 1), lst[1:]) # recursive step

关于python - 递归检查字母是否在给定字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54593123/

相关文章:

python numpy arange : strange behavior

Python - 从带有链接的网页下载 CSV 文件

php - 如何删除对象或数组中的递归?

python - 在实现二叉搜索树时,Python 中的最大递归深度超出了错误

recursion - Kotlin尾递归函数导致堆栈溢出

python - Pytest 覆盖范围 : run cov over multiple folders

python - 修复由列表列表创建的数据框

Python 属性错误 : 'module' object has no attribute 'Serial'

转换为碱基会得到相反的输出。如何在没有strrev的情况下使其正确?

c - 递归混淆