无法使我的count函数在Python中工作

2024-04-20 01:11:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数,你可以在“香蕉”一词中放入“ana”这样的短语,并计算它在该词中找到该短语的次数。我找不到我的一些测试单元不工作的错误。

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()

Tags: theintestdefcountlinemsgnum
3条回答

通过测试,将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

你用错了迭代,所以:

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   

使用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

相关问题 更多 >