简体   繁体   English

如何使用 python 中的递归检查一个字符串是否是另一个字符串的后续?

[英]How to check whether a string is subsequent of another string using recursion in python?

Goal: So my goal is to Write a recursive function is_subsequent that, given two strings, returns whether the first string is a subsequence of the second.目标:所以我的目标是编写一个递归 function is_subsequent,给定两个字符串,返回第一个字符串是否是第二个字符串的子序列。 FOR EXAMPLE, given hac and cathartic, you should return true, but given bat and table, you should return false.例如,给定 hac 和 cathartic,你应该返回 true,但给定 bat 和 table,你应该返回 false。

I have tried to write a code to check if one string is substring of the other.我试图编写一个代码来检查一个字符串是否是另一个字符串的 substring。 Here is my code:这是我的代码:

def is_subsequent(str1, str2):
    x = 0
    if (all(i in str2 for i in str1)):
        x = 1
    if (x):
        return True
    else:
        return False

But it doesn't care about the order of the string.但它不关心字符串的顺序。 I want to write a code that that takes in account the order as mentioned in the goal.我想编写一个考虑到目标中提到的顺序的代码。 And solve it using RECURSION.并使用递归解决它。

The basic idea behind recursion is that your function does two different things:递归背后的基本思想是您的 function 做了两个不同的事情:

  1. If the answer is really easy, it returns the answer.如果答案真的很简单,它会返回答案。 (This is a "base case".) (这是一个“基本情况”。)
  2. Otherwise, it figures out a way to make the problem easier, and calls itself to solve the easier version of the problem.否则,它会想办法让问题变得更简单,并调用自己来解决问题的更简单版本。 (A function calling itself is what's meant by "recursion.") (调用自身的 function 是“递归”的意思。)

In the case of this problem, you have two base cases:在这个问题的情况下,您有两个基本情况:

  1. If the first string is empty, it's a subsequence of anything , so that's True .如果第一个字符串为空,则它是 any 的子序列,因此为True
  2. If the second string is empty (and the first string isn't), nothing can be a subsequence of it, so that's False .如果第二个字符串为空(而第一个字符串不是),则没有任何内容可以是它的子序列,因此为False

Then you have two ways to make the problem easier (ie by making one or both strings smaller):然后你有两种方法可以使问题变得更容易(即通过使一个或两个字符串更小):

  1. If the first characters match, then the answer is the same as if you called the function on both strings minus the first letter.如果第一个字符匹配,则答案与您在减去第一个字母的两个字符串上调用 function 相同。 (That is, ac is a subsequence of artic IFF c is a subsequence of rtic .) (也就是说, acartic IFF c的子序列rtic的子序列。)
  2. If not, then the answer is the same as if you used the same first string but minus the first letter of the second string (That is, hac is a subsequence of cathartic IFF hac is a subsequence of athartic .)如果不是,那么答案与您使用相同的第一个字符串但减去第二个字符串的第一个字母相同(也就是说, haccathartic的子序列 IFF hacathartic的子序列。)
>>> def is_subsequence(needle: str, haystack: str) -> bool:
...     if not needle:
...         return True
...     if not haystack:
...         return False
...     if needle[0] == haystack[0]:
...         return is_subsequence(needle[1:], haystack[1:])
...     return is_subsequence(needle, haystack[1:])
...
>>> is_subsequence("hac", "cathartic")
True
>>> is_subsequence("bat", "table")
False

With the way you phrased your question in regards to the logic in the code that you posted there seems to be a disconnect...就您发布的代码中的逻辑而言,您提出问题的方式似乎存在脱节......

You have made it clear that making this a recursive function is a requirement but having your function use the keyword all and just checking the str1 for all of the characters in str2 would all but defeat the logic in creating a recursive function.您已经明确表示,将其设为递归 function 是一项要求,但让您的 function 使用关键字all并且仅检查str1中的所有字符str2将完全破坏创建递归 ZA3854F1AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZZA3851AB4ZZA3841AB4ZA384F1AB4ZA384F1AB5074C17A94F14Z 使用关键字 all 关键字 all 并仅检查 str1 中所有字符的逻辑。

You could pass an extra variable and remove characters on each subsequent recursive call with a terminating statement on each pass that will give you correct output.您可以在每个后续递归调用中传递一个额外的变量并删除字符,并在每次传递时使用一个终止语句,这将为您提供正确的 output。

def is_subsequent(search, text):
    if len(text) < len(search):
        return False
    for i, c in enumerate(search):
        if c != text[i]:
            return is_subsequent(search, text[1:])
    return True

This function checks if the search string is at least as long as the text string.此 function 检查搜索字符串是否至少与文本字符串一样长。
If so, check each character of the search string in turn to see if it matches with the text string.如果是,则依次检查搜索字符串的每个字符,看它是否与文本字符串匹配。
If the character ever does not match, try the function again, but from 1 place further in the text.如果字符不匹配,请再次尝试 function,但从文本中的 1 个位置开始。

This up here is a helper functions which deals with trivial cases, like the subsequence being empty which will always return true, or the subsequence being bigger than the other string or the other string being empty and the subsequence not, which will always return false.这里是一个辅助函数,用于处理琐碎的情况,例如子序列为空,它将始终返回 true,或者子序列大于另一个字符串,或者另一个字符串为空,而子序列不是,它将始终返回 false。

def is_subsequent(str1, str2):
    if str1 == "":
        return True
    elif str2 == "" or len(str1) > len(str2):
        return False
    else:
        return _is_subsequent(str1, str2, 0, 0)

This function here takes both strings and two pointers which always indicate the position of where you are currently comparing in both strings, alternatively you could use two substrings and always compare their first characters.这里的 function 采用两个字符串和两个指针,它们始终指示您当前在两个字符串中比较的位置的 position,或者您可以使用两个子字符串并始终比较它们的第一个字符。

If either of the pointers reaches an index that is no longer within the bounds of the string it is time to evaluate.如果任何一个指针到达不再在字符串范围内的索引,则该进行评估了。 If the i-pointer has reached the end we return true, if not we return false.如果 i-pointer 已到达末尾,则返回 true,否则返回 false。

def _is_subsequent(str1, str2, i, j):
    if i >= len(str1) or j >= len(str2):
        return i >= len(str1)
    if str1[i] == str2[j]:
        return _is_subsequent(str1, str2, i + 1, j + 1)
    else:
        return _is_subsequent(str1, str2, i, j + 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用迭代器检查python中字符串的后续元素? - How to check subsequent elements of string in python using iterators? 如何使用递归(python)检查string1是否与string2相反 - How to check if string1 is the reverse of string2 using recursion (python) 如何在Python中检查字符是否在字符串中的另一个字符之前 - How to check whether a character comes before another character in a string in Python 如何使用 Python 检查字符串是否由单个重复数字组成 - How to check whether or not a string consists of a single repeating digit using Python 如何检查输入字符串是否在 Python 中的另一个字符串中有字母? - How do I check whether an input string has alphabets in another string in Python? Python:使用递归查看一个字符串是否是另一字符串的旋转 - Python: using recursion to see if one string is a rotation of another Python 使用递归反转字符串 - Python reversing a string using recursion 你如何在python中检查一个字符串是否只包含数字? - How do you check in python whether a string contains only numbers? 如何在Python中检查raw_input是否为整数,字符串和日期 - how to check whether raw_input is integer, string and date in python 在python中,如何检查字符串是否以特殊符号开头? - In python How do i check whether a string starts with special symbol or not?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM