2011-07-30 84 views
-1

在本節中,我們給出了一系列單元測試,並且需要創建一個使測試通過的函數。這裏是測試:在學習Python時遇到一些麻煩練習方法48

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 
+0

我可以推薦你在codereview.stackexchange.com上發佈這段代碼嗎?你會得到一些關於如何使它更乾淨,更好的建議。 –

+0

最好不要使用固定代碼更新您的帖子。如果您想要包含固定代碼,請在原始代碼後添加它。這樣的問題仍然是有道理的。 –

回答

0

我懷疑,你一定要def scan(self, s):而不是def scan(s):

+0

我覺得他寧願'@ staticmethod',因爲用你的建議('self'),'lexicon.scan(「...」)'不起作用,因爲它需要一個對象。 – pts

1

只需將@staticmethod加上def scan(s):即可使其正常工作。

+0

當我這樣做時,它返回這個錯誤消息:NameError:全局名稱'convert_number'未定義 – Adam

+0

@Adam用'lexicon.convert_number'替換'convert_number'。 –

+0

@phaedrus好吧,但是這給了我這個錯誤消息:TypeError:必須使用詞典實例調用unbound方法convert_number()作爲第一個參數(代替str實例) – Adam