【问题标题】:Can't get my count function to work in Python无法让我的计数函数在 Python 中工作
【发布时间】:2012-01-06 13:46:46
【问题描述】:

我正在尝试创建一个函数,您可以在其中将诸如“ana”之类的短语放入单词“banana”中,并计算它在单词中找到该短语的次数。我找不到让我的某些测试单元无法工作的错误。

def test(actual, expected):
    """ Compare the actual to the expected value,
        and print a suitable message.
    """
    import sys
    linenum = sys._getframe(1).f_lineno   # get the caller's line number.
    if (expected == actual):
        msg = "Test on line {0} passed.".format(linenum)
    else:
        msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'.".format(linenum, expected, actual))
    print(msg)

def count(phrase, word):
    count1 = 0
    num_phrase = len(phrase)   
    num_letters = len(word)    

    for i in range(num_letters):
        for x in word[i:i+num_phrase]:
             if phrase in word:
                 count1 += 1
             else:
                 continue    
        return count1

def test_suite():
    test(count('is', 'Mississippi'), 2)
    test(count('an', 'banana'), 2)
    test(count('ana', 'banana'), 2)
    test(count('nana', 'banana'), 1)
    test(count('nanan', 'banana'), 0)
    test(count('aaa', 'aaaaaa'), 4)

test_suite()

【问题讨论】:

  • 有什么错误?附言请减少多余的空行,以使您的问题更具可读性。谢谢。
  • 您在 word[] 中对 x 的迭代对我来说没有意义。
  • 你的变量名很混乱。例如,num_phrase 不是短语的编号,而是它的长度。 x完全是非描述性的。根据我的经验,整理术语往往会在短时间内发现问题。

标签: python function python-3.x


【解决方案1】:

将您的 count 函数更改为以下通过测试:

def count(phrase, word):
    count1 = 0
    num_phrase = len(phrase)   
    num_letters = len(word)    
    for i in range(num_letters):
        if word[i:i+num_phrase] == phrase:
          count1 += 1
    return count1

【讨论】:

  • 谢谢。我不知道我怎么忽略了这一点。我想我只是让我的功能太复杂了。
  • 如果您正在搜索和/或在大字符串中,有几个algorithms 可以加快搜索速度。
【解决方案2】:

使用str.count(substring)。这将返回子字符串在完整字符串中出现的次数 (str)。

这是一个展示其工作原理的交互式会话:

>>> 'Mississippi'.count('is')
2
>>> 'banana'.count('an')
2
>>> 'banana'.count('ana')
1
>>> 'banana'.count('nana')
1
>>> 'banana'.count('nanan')
0
>>> 'aaaaaa'.count('aaa')
2
>>> 

如您所见,函数不重叠。如果您需要重叠行为,请看这里:string count with overlapping occurrences

【讨论】:

    【解决方案3】:

    你用错了迭代,所以:

    for i in range(num_letters):   #This will go from 1, 2, ---> len(word)    
    
        for x in word[i:i+num_phrase]:  
        #This will give you the letters starting from word[i] to [i_num_phrase] 
        #but one by one, so :  for i in 'dada': will give you 'd' 'a' 'd' 'a'
    
             if phrase in word:       #This condition doesnt make sense in your problem, 
                                      #if it's true it will hold true trough all the 
                                      #iteration and count will be 
                                      #len(word) * num_phrase,                 
                                      #and if it's false it will return 0
                 count1 += 1
             else:
                 continue   
    

    【讨论】:

      【解决方案4】:

      我猜,str.count(substring) 是错误的解决方案,因为它不计算重叠的子字符串并且测试套件失败。

      还有内置的str.find 方法,可能对任务有所帮助。

      【讨论】:

        【解决方案5】:

        另一种方式:

        定义计数(序列,项目):

          count = 0
        
          for x in sequence :
        
             if x == item :
             count = count+1
          return count   
        

        【讨论】:

          【解决方案6】:

          这次提出了一个基本问题。

          当你看到像"isisisisisi" 这样的字符串时,你算了多少个“isi”?

          在第一个状态下,您会看到字符串 "isi s isi s isi" 并返回 3 作为计数。

          在第二种状态下,您会看到字符串"isisisisisi",并计算每个短语的“i”两次,例如"isi isi isi isi isi"。 换句话说,第二个“i”是第一个“isi”的最后一个字符和第二个“isi”的第一个字符。

          所以你必须返回 5 作为计数。

          对于第一个状态,只需使用:

          >>> string = "isisisisisi"
          >>> string.count("isi")
          3
          

          对于第二种状态,您必须识别搜索关键字中的"phrase"+"anything"+"phrase"

          下面的函数可以做到:

          def find_iterate(Str):
               i = 1
               cnt = 0
               while Str[i-1] == Str[-i] and i < len(Str)/2:
                   i += 1
                   cnt += 1
               return Str[0:cnt+1]
          

          现在您有很多选择来计算字符串中的搜索关键字。

          例如我在下面这样做:

          if __name__ == "__main__":
              search_keyword = "isi"
              String = "isisisisisi"
              itterated_part = find_iterate(search_keyword)
              c = 0
              while search_keyword in String:
                  c += String.count(search_keyword)
                  String = String.replace(search_keyword, itterated_part)
              print c
          

          我不知道python中是否有更好的方法。但是我尝试在正则表达式的帮助下做到这一点,但没有找到。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-11-11
            • 2020-12-10
            • 1970-01-01
            • 1970-01-01
            • 2020-08-25
            • 1970-01-01
            • 2021-02-10
            相关资源
            最近更新 更多