艰难地学习Python,练习48

2024-10-01 07:39:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我花了一整天的时间来解决书Learn Python The Hard Way中“Exercise 48: Advanced User Input”中的test_errors()函数。在

assert_equal(),测试中的一个函数要求我按顺序输入元组,但我无法这样编码。在

我的循环总是首先返回名词,最后返回错误元组,我不知道如何中断循环,以便它重新开始,但要使用正确的值来继续,或者使用任何必要的方法来按这些元组应该的顺序进行排序。在

代码如下:

class Lexicon(object):

def scan(self, stringo):
    vocabulary = [[('direction', 'north'), ('direction', 'south'), ('direction',     'east'), ('direction', 'west')],
                    [('verb', 'go'), ('verb', 'kill'), ('verb', 'eat')],
                    [('stop', 'the'), ('stop', 'in'), ('stop', 'of')],
                    [('noun', 'bear'), ('noun', 'princess')],    # Remember numbers
                    [('error', 'ASDFADFASDF'), ('error', 'IAS')],
                    [('number', '1234'), ('number','3'), ('number', '91234')]]

    self.stringo = stringo
    got_word = ''
    value = []
    rompe = self.stringo.split() #split rompe en los espacios

    for asigna in vocabulary: 
        for encuentra in asigna:          
            if encuentra[1]  in rompe:
                value.append(encuentra)

    return value   

eLexicon = Lexicon()


from nose.tools import *
from ex48.ex48 import eLexicon 

def test_directions():
    assert_equal(eLexicon.scan("north"), [('direction', 'north')])
    result = eLexicon.scan("north south east")
    assert_equal(result, [('direction', 'north'),
                  ('direction', 'south'),
              ('direction', 'east')])

def test_verbs():
    assert_equal(eLexicon.scan("go"), [('verb', 'go')])
    result = eLexicon.scan("go kill eat")
    assert_equal(result, [('verb', 'go'),
                  ('verb', 'kill'),
                  ('verb', 'eat')])

def test_stops():
    assert_equal(eLexicon.scan("the"), [('stop', 'the')])
    result = eLexicon.scan("the in of")
    assert_equal(result, [('stop', 'the'),
                  ('stop', 'in'),
                  ('stop', 'of')])

def test_nouns():
    assert_equal(eLexicon.scan("bear"), [('noun', 'bear')])
    result = eLexicon.scan("bear princess")
    assert_equal(result, [('noun', 'bear'),
                  ('noun', 'princess')])

#def test_numbers():
#   assert_equal(lexicon.scan("1234"), [('number', 1234)])
#   result = lexicon.scan("3 91234")
#   assert_equal(result, [('number', 3),
#                 ('number', 91234)])

def test_errors():
    assert_equal(eLexicon.scan("ASDFADFASDF"), [('error', 'ASDFADFASDF')])
    result = eLexicon.scan("bear IAS princess")
    assert_equal(result, [('noun', 'bear'),
                  ('error', 'IAS'),
                  ('noun', 'princess')])

======================================================================
FAIL: tests.ex48_tests.test_errors
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/home/totoro/Desktop/Python/projects/ex48/tests/ex48_tests.py", line 43, in         test_errors
    ('noun', 'princess')])
AssertionError: Lists differ: [('noun', 'bear'), ('noun', 'p... != [('noun', 'bear'),     ('error', '...

First differing element 1:
('noun', 'princess')
('error', 'IAS')

- [('noun', 'bear'), ('noun', 'princess'), ('error', 'IAS')]
+ [('noun', 'bear'), ('error', 'IAS'), ('noun', 'princess')]

----------------------------------------------------------------------
Ran 5 tests in 0.006s

非常感谢您抽出时间。在


Tags: intestscandeferrorassertequalresult
3条回答
    for word in self.stringo.split(): 
        for pair in vocabulary:             
            if pair[0][1] == word:
                value.append(pair[0])
            elif pair[1][1] == word:
                value.append(pair[1])
            elif pair[2][1] == word:
                value.append(pair[2])
            elif pair[3][1] == word:
                value.append(pair[3])

测试中单词的顺序与单词的顺序相同。因此,您需要重新排序for-循环,以便首先迭代输入:

    value = []
    for rompe in stringo.split():
        for asigna in vocabulary:
            for encuentra in asigna:
                if encuentra[1] == rompe:
                    value.append(encuentra)

这将以正确的顺序返回encuentra。在

注1:不应硬编码数字或错误。在

注2:您可以通过使用一两个字典来大幅降低此算法的复杂度。在

示例:

^{pr2}$

这对我来说很好,它是较短的代码。这本书是前段时间写的,幸好我还有档案。。。在

def check(word):
    lexicon = {
        'direction': ['north', 'south', 'east', 'west'],
        'verb': ['go', 'kill', 'eat'],
        'stop': ['the', 'in', 'of'],
        'noun': ['bear', 'princess'],
        'error': ['ASDFADFASDF', 'IAS']
    }
word = str(word)
for key in lexicon:
    if word in lexicon[key]:
        return (key, word)
    elif word.isdigit():
        return ('number', int(word))

def scan(words):
    words = words.split()
    to_return = []
    for i in words:
        to_return.append(check(i))
    return to_return

结果是:

^{pr2}$

告诉我这个代码是否有错误。请在下面评论:D

相关问题 更多 >