在本节中,我们给出了一系列单元测试,并且需要创建一个使测试通过的函数。这里是测试:在学习Python时遇到一些麻烦练习方法48
from nose.tools import *
from testing import *
def test_numbers():
assert_equal(scan("1234"), [('number', 1234)])
result = scan("3 91234")
assert_equal(result, [('number', 3),
('number', 91234)])
还有其他方面的测试,但这是唯一一个没有通过。下面是我写的:
def convert_number(s):
try:
return int(s)
except ValueError:
return None
def scan(s):
direction_words= ("north", "south", "east", "west", "down", "up", "left", "right", "back")
verbs= ("go", "stop", "kill", "eat")
stop_words= ("the", "in", "of", "from", "at", "it")
nouns= ("door", "bear", "princess", "cabinet")
numbers= s.split()
i=0
j=0
g=0
m=0
a=0
while a< len(numbers):
if type(convert_number(numbers[a])) == int:
return [('number', int(x)) for x in s.split()]
else:
a += 1
while i < 9:
if direction_words[i] in s.split():
return [('direction', x) for x in s.split()]
else:
i+=1
while j < 4:
if verbs[j] in s.split():
return [('verb', x) for x in s.split()]
else:
j+=1
while g < 6:
if stop_words[g] in s.split():
return [('stop', x) for x in s.split()]
else:
g+=1
while m < 4:
if nouns[m] in s.split():
return [('noun', x) for x in s.split()]
else:
m+=1
else:
return
我可以推荐你在codereview.stackexchange.com上发布这段代码吗?你会得到一些关于如何使它更干净,更好的建议。 –
最好不要使用固定代码更新您的帖子。如果您想要包含固定代码,请在原始代码后添加它。这样的问题仍然是有道理的。 –