簡體   English   中英

在Python中遞歸搜索目標字符串中的鍵字符串

[英]Searching for key string within target string in Python recursively

以下是針對Python 3.2.3的版本。


我想編寫一個帶有兩個參數的函數,一個鍵字符串和一個目標字符串。 這些功能用於遞歸確定(必須是遞歸的)鍵字符串在目標字符串中的位置。

目前,我的代碼如下。

def posSubStringMatchRecursive(target,key):
    import string
    index=str.rfind(target, key)
    if index !=-1:
        print (index)
        target=target[:(index+len(key)-1)]
        posSubStringMatchRecursive(target,key)

這樣做的問題是,無法將關鍵字字符串的所有位置存儲在列表的目標字符串中,因為指示位置的數字只會被打印出來。

所以,我的問題是, 有什么辦法可以更改代碼,以便可以將目標字符串中的密鑰字符串的位置存儲在列表中


示例輸出

countSubStringMatchRecursive ('aatcgdaaaggraaa', 'aa')

13
12
7
6
0

編輯

以下代碼似乎可以正常工作,而Ashwini的代碼中沒有這個問題。 謝謝,列夫

def posSubStringMatchRecursive(target,key):
    import string
    index=str.rfind(target, key)
    if index ==-1:
        return []
    else:
        target=target[:(index+len(key)-1)]
        return ([index] + posSubStringMatchRecursive(target,key))

由於它可疑地類似於一個作業問題,因此下面是一個返回列表的遞歸函數示例:

In [1]: def range_rec(limit):
    if limit == 0:
        return []
    else:
        return ([limit-1] + range_rec(limit-1)[::-1])[::-1]
   ...: 

In [2]: range_rec(10)
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def posSubStringMatchRecursive(target,key,res):
    import string
    index=str.rfind(target, key)
    if index !=-1:

        target=target[:(index+len(key)-1)]
        res.append(index) #append the index to the list res, 
        return posSubStringMatchRecursive(target,key,res) #Use return here when calling recursively else your program will return None, and also pass res to the function
    else:
        return res

 print(posSubStringMatchRecursive('aatcgdaaaggraaa', 'aa',[]))#pass a empty list to the function
print(posSubStringMatchRecursive('aatcgdaaaggraaa', 'a',[]))

輸出:

[13, 12, 7, 6, 0]`
[14, 13, 12, 8, 7, 6, 1, 0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM