【问题标题】:Having some trouble with Learn Python The Hard Way Excercise 48Learn Python The Hard Way Excercise 48 遇到一些麻烦
【发布时间】: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


【解决方案1】:

只需在def scan(s): 上方添加@staticmethod 即可。

【讨论】:

  • 当我这样做时,它返回此错误消息:NameError: global name 'convert_number' is not defined
  • @Adam 将 convert_number 替换为 lexicon.convert_number
  • @phaedrus 好的,但这给了我这个错误信息:TypeError: unbound method convert_number() must be called with lexicon instance as first argument (got str instance)
  • @Adam:你需要@staticmethoddefs之上。如果这不能解决问题,请使用您正在运行的代码和完整的(多行)错误消息(包括行号和文件名)更新您的问题。
  • @pts 我一直在弄乱代码以尝试解决一些问题,我只是用最新版本更新了它,错误消息我无法弄清楚。
【解决方案2】:

我怀疑你肯定想要def scan(self, s): 而不是def scan(s):

【讨论】:

  • 我认为他更需要@staticmethod,因为根据你的建议 (self),lexicon.scan("...") 将不起作用,因为它需要一个对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 2011-05-25
  • 1970-01-01
  • 2014-05-26
  • 1970-01-01
相关资源
最近更新 更多