[英]How to check whether a string is subsequent of another string using recursion in python?
目標:所以我的目標是編寫一個遞歸 function is_subsequent,給定兩個字符串,返回第一個字符串是否是第二個字符串的子序列。 例如,給定 hac 和 cathartic,你應該返回 true,但給定 bat 和 table,你應該返回 false。
我試圖編寫一個代碼來檢查一個字符串是否是另一個字符串的 substring。 這是我的代碼:
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
但它不關心字符串的順序。 我想編寫一個考慮到目標中提到的順序的代碼。 並使用遞歸解決它。
遞歸背后的基本思想是您的 function 做了兩個不同的事情:
在這個問題的情況下,您有兩個基本情況:
True
。False
。然后你有兩種方法可以使問題變得更容易(即通過使一個或兩個字符串更小):
ac
是artic
IFF c
的子序列rtic
的子序列。)hac
是cathartic
的子序列 IFF hac
是athartic
的子序列。)>>> 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
就您發布的代碼中的邏輯而言,您提出問題的方式似乎存在脫節......
您已經明確表示,將其設為遞歸 function 是一項要求,但讓您的 function 使用關鍵字all
並且僅檢查str1
中的所有字符str2
將完全破壞創建遞歸 ZA3854F1AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZA3851AB4ZZA3851AB4ZZA3841AB4ZA384F1AB4ZA384F1AB5074C17A94F14Z 使用關鍵字 all 關鍵字 all 並僅檢查 str1 中所有字符的邏輯。
您可以在每個后續遞歸調用中傳遞一個額外的變量並刪除字符,並在每次傳遞時使用一個終止語句,這將為您提供正確的 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
此 function 檢查搜索字符串是否至少與文本字符串一樣長。
如果是,則依次檢查搜索字符串的每個字符,看它是否與文本字符串匹配。
如果字符不匹配,請再次嘗試 function,但從文本中的 1 個位置開始。
這里是一個輔助函數,用於處理瑣碎的情況,例如子序列為空,它將始終返回 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)
這里的 function 采用兩個字符串和兩個指針,它們始終指示您當前在兩個字符串中比較的位置的 position,或者您可以使用兩個子字符串並始終比較它們的第一個字符。
如果任何一個指針到達不再在字符串范圍內的索引,則該進行評估了。 如果 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.