【发布时间】: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