2016-02-26 20 views
1

我是一個noob,這是w/r/t python 2.7和一個練習我正在努力通過瞭解Python的難題link to ex47) - 下面的文件名爲ex47_tests.py,我得到的錯誤與運行nosetests到我在工作目錄nosetest錯誤:ValueError:字典更新序列元素#0具有長度4; 2是必需的

nosetests,錯誤是在該行west.add_paths({'east', start})test_map()功能,它指出:ValueError: dictionary update sequence at element #0 has length 4; 2 is required,但我不明白是什麼問題...這是測試文件:

from nose.tools import * 
from ex47.game import Room 


def test_room(): 
    gold = Room("GoldRoom", 
       """This room has gold in it you can grab. There's a 
       door to the north.""") 
    assert_equal(gold.name, "GoldRoom") 
    assert_equal(gold.paths, {}) 

def test_room_paths(): 
    center = Room("Center", "Test room in the center.") 
    north = Room("North", "Test room in the north.") 
    south = Room("South", "Test room in the south.") 

    center.add_paths({'north': north, 'south':south}) 
    assert_equal(center.go('north'), north) 
    assert_equal(center.go('south'), south) 

def test_map(): 
    start = Room("Start", "You can go west and down a hole.") 
    west = Room("Trees", "There are trees here, you can go east.") 
    down = Room("Dungeon", "It's dark down here, you can go up.") 

    start.add_paths({'west': west, 'down': down}) 
    west.add_paths({'east', start}) 
    down.add_paths({'up': start}) 

    assert_equal(start.go('west'), west) 
    assert_equal(start.go('west').go('east'), start) 
    assert_equal(start.go('down').go('up'), start) 

作爲參考,game.py文件包含Room類具有add_paths函數(方法):

class Room(object): 

    def __init__(self, name, description): 
     self.name = name 
     self.description = description 
     self.paths = {} 

    def go(self, direction): 
     return self.paths.get(direction, None) 

    def add_paths(self, paths): 
     self.paths.update(paths) 

我檢查了幾次,我已經成功地在遊戲中運行的代碼west.add_paths({'east', start}) .py文件,但是當我運行nosetests時,我不斷收到相同的錯誤。在發生錯誤的代碼中,我的解釋是,west包含一個空的{},應該沒有問題update,否?有人可以提供一些見解,爲什麼這不起作用,錯誤來自哪裏?

非常感謝。

回答

1

在代碼中的錯誤是從這個函數來:

west.add_paths({'east', start}) 

修正與此進行,是要與字典更新,沒有一套:

west.add_paths({'east': start}) 

當您嘗試更新帶有集的字典時,此錯誤對於以下示例是可重現的:

>>> d = {} 
>>> d.update({'east','start'}) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: dictionary update sequence element #0 has length 5; 2 is required 

爲客戶提供更清晰的錯誤,如果你去你的解釋,並檢查該類型:

通知「東」和「啓動」

>>> print(type({'east', 'start'})) 
<type 'set'> 

通知東之間」冒號之間的逗號'和‘開始’

>>> print(type({'east': 'start'})) 
<type 'dict'> 
+0

嗨idjaw,nosetests告訴我,源於所以很容易找到錯誤的行,我明白你的錯誤重新制作,但我想我很困惑,爲什麼當我測試'game.py內的west.add_paths({'east':start})'我沒有收到錯誤。我在'update'之前檢查'west.path',之後'update'和'west.path',並且我成功地看到房間對象將它放入空{}中。 – jmb277

+0

嘿@ jmb277! :)再仔細看看你寫的是什麼。你寫這個:'{'東':開始}'。看看我在解決方案中寫到的第一行代碼,它寫成:'{'east',start}'。注意東方和開始之間的逗號。 * *表示錯誤。 – idjaw

+0

嗨idjaw,我嚴肅地看着你放下的那兩個代碼片段,我想知道如果我被拖動了B/C,我完全錯過了':'vs','差異 - 現在工作,我真的很感謝你的耐心 - 謝謝。 – jmb277

相關問題