python - 艰难地学习Python ex48 [内存错误]

标签 python

我已经完成了下面的代码(尚未完成数字和错误扫描部分),但 Nose 测试结果告诉我存在内存错误。我不明白出了什么问题..

这是我的代码:

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

最佳答案

        else:
            result.append((b,a))
            c == 1

在这种情况下, c 都不是也不x改变,从而循环 while x < len(word_type) and c == 0:继续运行,result不断增长并消耗所有内存。

我不确定你是否想要c = 1c += 1 ,但不太可能是c == 1因为它是一个空操作。您没有使用相等比较的结果。

关于python - 艰难地学习Python ex48 [内存错误],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37192593/

相关文章:

python - Kivy 布局高度适应子部件的高度

python - 函数的输入参数是否总是默认返回?

python - 如何将元组变成元组的元组?

python - while循环运行一次?

python - 使用 Python 将现有 netcdf 文件中的 Nans 替换为 -9999

python - 以可测试的方式连接到 mongodb

python - 使用 pymodbus 读取寄存器

python - 从我的计算机python中提取子网掩码

python - 在遍历字典的同时修改字典。 Python 字典中的错误?

python - SVM 实现,scikit 学习减少运行时间,最快的 svm