我已完成下面的代码,(尚未完成数字和错误扫描部分),但测试结果告诉我存在内存错误。我不知道怎么回事......
这是我的代码:
class lexicon(object):
def __init__(self):
pass
def scan(self, sentence):
direction = ["north", "south", "east", "west", "dwon", "up", "left", "right", "back"]
verb = ["go", "stop", "kill", "eat"]
stop = ["the", "in", "of", "from", "at", "it"]
noun = ["door", "bear", "princess", "cabinet"]
word_type = [direction, verb, stop, noun]
wordlist = sentence.split()
result = []
for a in wordlist:
x = 0
c = 0
while x < len(word_type) and c == 0:
b = word_type[x]
if a not in b:
x += 1
else:
result.append((b,a))
c == 1
if x == len(word_type):
result.append(("error",a))
return result
这是test_lexicon:
from nose.tools import *
from game48 import lexicon
def test_directions():
lexicon1 = lexicon()
assert_equal(lexicon1.scan("north"),[("direction","north")])
result = lexicon.scan("notrh south east")
assert_equal(result, [("direction", "north"), ("direction", "south"), ("direction", "east")])
这就是结果:
ERROR: tests.lexicon_tests.test_directions
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\users\sine\appdata\local\programs\python\python35-32\lib\site-packages\nose\case.py", line 198, in runTest
self.test(*self.arg)
File "E:\Python\exercises of learn python the hard way\ex48\tests\lexicon_tests.py", line 6, in test_directions
assert_equal(lexicon1.scan("north"),[("direction","north")])
File "E:\Python\exercises of learn python the hard way\ex48\game48.py", line 26, in scan
result.append((b,a))
MemoryError
======================================================================
ERROR: tests.lexicon_tests.test_verbs
答案 0 :(得分:1)
else:
result.append((b,a))
c == 1
在这种情况下c
和x
都没有改变,因此循环while x < len(word_type) and c == 0:
一直在运行和运行,result
无限增长并消耗掉所有内存。
我不确定您是想要c = 1
还是c += 1
,但它不太可能是c == 1
因为它是无操作。你没有利用相等比较的结果。
答案 1 :(得分:0)
你可能想让c = 1,而不是c == 1。在这种情况下,没有什么会改变,你将有无限循环。
答案 2 :(得分:0)
除了循环问题之外,还有另一个问题,lexicon1.scan("north")
将最终返回:
[(["north", "south", "east", "west", "dwon", "up", "left", "right", "back"], "north")]
代替所需的:[('direction', 'north')]
我们可以解决这个问题,并简化代码,使用字典来保存单词:
class lexicon(object):
def __init__(self):
self.word_types = {
"direction": ["north", "south", "east", "west", "down", "up", "left", "right", "back"],
"verb": ["go", "stop", "kill", "eat"],
"stop": ["the", "in", "of", "from", "at", "it"],
"noun": ["door", "bear", "princess", "cabinet"]
}
def scan(self, sentence):
wordlist = sentence.split()
result = []
for word in wordlist:
for word_type in self.word_types:
if word in self.word_types[word_type]:
result.append((word_type, word))
break
else:
result.append(("error", word))
return result
请注意,else
循环上的for
与else
语句中的if
不同,可以认为它意味着“没有中断”,即如果永远不会达到break
语句并且循环用完就要执行的代码。