如何在没有导入的情况下递归地查找给定字符串是否是另一个给定字符串的子序列?

2024-05-14 14:23:02 发布

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

任务:

Write a recursive function named is_subsequence that takes two string parameters and returns True if the first string is a subsequence of the second string, but returns False otherwise. We say that string A is a subsequence of string B if you can derive A by deleting zero or more letters from B without changing the order of the remaining letters. You can assume that neither string contains upper-case letters.

You may use default arguments and/or helper functions.

Your recursive function must not: use imports. use any loops use any variables declared outside of the function. use any mutable default arguments.

到目前为止我拥有的内容(必须使用此格式):

def is_subsequence(strA, strB = None):
if strB == None:
   strB = []

print(is_subsequence("dog", "dodger"))

我的问题:
我不知道如何通过删除字母来递归地编辑字符串。(strB.replace("e","")不起作用)


Tags: andofthestringifthatisuse
1条回答
网友
1楼 · 发布于 2024-05-14 14:23:02

我不知道根据说明是否允许这样做,但我添加了一个索引参数,并能够得出这个结论。(代码片段是Python)

&13; 第13部分,;
def is_subsequence(strA, strB, index=0):
    """
    Function that determines if string A is a subsequence of string B
    :param strA: String to compare subsets to (strings are immutable)
    :param strB: Parent string to make subsets of (strings are immutable)
    :param index: number of combinations tested
    :return: True if a subsequence is found, False if index reaches maximum with none found
    """

    binary = '{:0{leng}b}'.format(index, leng=len(strB))

    if index > 2**len(strB)-1:  #If past maximum return False
        return False

    def makesub(sub="", pos=0):
        """
        Function that builds up the current subsequence being tested by using binary to choose letters
        :param sub: The currently selected letters
        :param pos: Position in binary string to compare
        :return: completed subsequence for comparing to strA
        """
        if pos > len(binary)-1: #If pos is passed the length of our binary number return the created subsequence
            return sub
        if binary[pos] == "1":  #If the pos in binary is a 1, add the letter to our sub. If it is 0 do nothing.
            sub = sub + strB[pos]

        return makesub(sub, pos + 1)    #increment pos and try again or return what the call returned

    if makesub() == strA:       #If the returned sub matches strA we found a matching subsequence, return True
        return True

    return is_subsequence(strA, strB, index + 1)    #increment index and try again or return what the call returned


print(is_subsequence("dog", "dodger"))
和#13;
和#13;

相关问题 更多 >

    热门问题