python - 无法让我的计数函数在 Python 中运行

标签 python function python-3.x

我正在尝试创建一个函数,您可以在该函数中将诸如“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()

最佳答案

将您的 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

关于python - 无法让我的计数函数在 Python 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8758768/

相关文章:

python - 在 Postgresql 中使用 uuid.uuid4() 或 secrets.token_urlsafe() 难以猜测 url 和快速选择?

python - 没有给出参数时选择解析器打印使用帮助

python : Appending values to existing spreadsheet from updated values

Pythonic 处理此错误情况

scala - Foo在Scala中不带参数编译错误?

python - 无参数输入的函数可变范围

python - 在python中为时间序列图添加趋势线

python - 函数什么时候被修饰,什么时候不被修饰?

function - 我正在寻找一种简单的解决方案,使用下面的现有代码单击缩略图,即可加载新的/不同的mp3声音文件

python - 读取h5数据集python的一部分