【发布时间】:2011-07-30 18:27:33
【问题描述】:
在本节中,我们得到了一系列单元测试,需要创建一个函数来使测试通过。这是测试:
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 上发布此代码吗?您将获得一些关于如何使其更清洁、总体上更好的建议。
-
最好不要使用固定代码更新您的帖子。如果要包含固定代码,请将其添加到原始代码之后。这样这个问题还是有道理的。
标签: python python-2.7