【问题标题】:Problem with a User Define Function in PythonPython中用户定义函数的问题
【发布时间】:2011-08-19 05:47:48
【问题描述】:

好的,这就是我的问题,我定义了一个函数来计算某个片段在字符串中出现的次数。该函数从 Index[0] 开始搜索,随后的搜索从字符串中最后一个匹配项的索引开始。

这是代码

def function(fragment, string):
    count = -1
    last_match = 0
    while last_match != -1:
        count += 1
        last_match = string.find(fragment, last_match)
    return count

现在问题来了,当将参数传递给带有明显匹配字符串的片段的函数时,我得到一个无限循环。 当我修复无限循环时,如果位于 Index[0] 中的传递片段,该函数不会返回正确的计数???

例如:
function('gtg' , 'gttacgtggatg' ) This gives me an infinite loop

function('gtt' , 'gttacgtggatg' ) This doesn't return a count..

只是寻求一些帮助和意见..

谢谢

【问题讨论】:

    标签: python function


    【解决方案1】:

    如果可能,您应该使用现有功能:

    "aabbccaabb".count("aa")
    

    count 方法完全符合您的要求。上面的例子返回 2。

    【讨论】:

      【解决方案2】:

      你有两个错误:

      1. 字符串文档指出,如果未找到片段,find 将返回 -1
      2. last_match 返回匹配开始的索引,因此如果您从该索引再次搜索,您会一次又一次地找到相同的匹配。

      所以你可能不得不使用这个:

      def function(fragment, string):
          count = -1
          last_match = 0
          while last_match != -1:
              count += 1
              last_match = string.find(fragment, last_match)
              if last_match != -1:
                  last_match += 1
          return count
      
      >>> function('gtt' , 'gttacgtggatg' )
      1
      >>> function('gtg' , 'gttacgtggatg' )
      1
      

      当然,如果您对重叠匹配不感兴趣,您也可以依赖 string.count(fragment)...或前面的答案提到的正则表达式...

      >>> 'gttacgtggatg'.count('ctt')
      0
      >>> 'gttacgtggatg'.count('gtt')
      1
      

      【讨论】:

        【解决方案3】:

        您是否考虑过使用正则表达式?它非常适合您的使用。 Python re module

        更新:为了扩展它,如果你做这样的事情......

        重新导入

        ...

        def countOccurrences(myFragment, myString): expr = re.compile(myFragment) 返回 len(expr.findall(myString))

        【讨论】:

        • 不,不是真的,我认为不使用 RE 也有解决问题的办法。我只是想着想着就累了。;-) 也许我会休息一下以全新的心态回到 2 毫米。
        • 我认为 Achim 的计数方法是正确的。为了存档,我将把帖子留在这里。
        【解决方案4】:

        从逻辑上讲,您的问题是您只是一遍又一遍地找到相同的匹配项:

        last_match = string.find(fragment, last_match)
        

        ...将从您找到最后一场比赛的位置开始,这只会让您回到相同的位置!您需要使用string.find(fragment, last_match + 1),这将要求您跳过箍以使用哨兵作为您的初始值last_match

        Achim's answer 答案很准确:您应该使用现有的功能来做到这一点。

        【讨论】:

        • 你绝对正确,这就是为什么我说当我修复无限循环时一切都很好,直到作为参数传递的片段从字符串中的 Index[0] 开始..
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-06
        • 2011-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-13
        • 1970-01-01
        相关资源
        最近更新 更多