【问题标题】:Searching for key string within target string in Python recursively在Python中递归搜索目标字符串中的键字符串
【发布时间】:2012-06-25 11:23:11
【问题描述】:

以下内容适用于 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))

【问题讨论】:

  • 为什么一定要递归?如果这是一个家庭作业问题,请tag它本身
  • 我有一个漂亮而干净的迭代方法,我只是想知道您是否可以递归生成一个列表,因为递归版本的运行时似乎更快(对于小样本)
  • 老实说,问题来自 [link]ocw.mit.edu/courses/electrical-engineering-and-computer-science/… 但这并不是我的功课

标签: python string search python-3.x


【解决方案1】:
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]

【讨论】:

  • 现在尝试再次调用它:) 重复 print 行,例如。
  • @LevLevitsky 正如我所提到的,它充当静态变量,并且每次调用都会保持值,所以它只适用于一次调用。
  • @LevLevitsky 我编辑了我的解决方案,使其适用于多个呼叫。
【解决方案2】:

由于它可疑地类似于家庭作业问题,下面是一个返回列表的递归函数示例:

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]

【讨论】:

  • 我已经处理了您的代码并编辑了我自己的问题。感谢您的指导。
  • @VincentTjeng 您可能想accept 答案之一。
  • 如果可以的话,我会投票赞成你的答案,但不幸的是我没有足够的代表。对不起!
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 2019-03-13
  • 2016-07-04
相关资源
最近更新 更多