我正在嘗試創建一個函數,您可以在單詞「香蕉」中插入「ana」等短語,然後計算它找到該短語的次數在這個詞裏。我無法找到我爲某些測試單元所做的錯誤而無法工作。無法讓我的計數函數在Python中工作
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()
什麼錯誤?附:請減少多餘的空行,讓您的問題更具可讀性。謝謝。 – 2012-01-06 13:53:20
你在字[]中對x的迭代對我沒有意義。 – 2012-01-06 13:54:52
你的變量名稱很混亂。例如'num_phrase'不是一個短語的數字,但是它的* length * * x'完全*是非描述性的。根據我的經驗,整理術語往往會在短期內發現問題。 – kindall 2012-01-06 19:32:22