2014-04-15 109 views
0

我有以下單元測試問題,我試圖通過。Python對象測試

def test_map2(self): 
    self.home = [] 
    self.home.append(Bed('Bedroom')) 
    self.home.append(Sofa('Living Room')) 
    self.home.append(Table('Bedroom')) 

    mapping = map_the_home(self.home) 
    self.assertTrue(isinstance(mapping['Bedroom'][0], Bed)) 
    self.assertTrue(isinstance(mapping['Living Room'][0], Sofa)) 
    self.assertTrue(isinstance(mapping['Bedroom'][1], Table)) 

每個值都應該是一個列表,裏面有一個或多個Furnishing子類實例。

這是我目前的嘗試。

class Furnishing(object):  
    def __init__(self, room): 
     self.room = room 

class Sofa(Furnishing):  
    name = 'Sofa' 

class Bed(Furnishing):  
    name = 'Bed' 

class Table(Furnishing):  
    name = 'Table' 

def map_the_home(home):  
    results = {} 

    for furnitiure in home:  
     if furnitiure.room in results:     
      results[furnitiure.room] = (results[furnitiure.room],furnitiure)  
     else:  
      results[furnitiure.room] = furnitiure   
    return results 

def counter(home):  
    counter_list = {} 
    for line in home:  
     if line.name in counter_list: 
      print(line.room,line.name) 
      counter_list[line.name] = counter_list[line.name] + 1  
     else:  
      counter_list[line.name] = 1  

    for furniture in counter_list:  
     print('{0} = {1}'.format(furniture,counter_list[furniture])) 

if __name__ == "__main__":  
    home = [] 
    home.append(Bed('Bedroom')) 
    home.append(Sofa('Living Room')) 
    home.append(Table('Bedroom')) 
    map_the_home(home) 
    counter(home) 

該計數器只是另一部分,但希望給出完整的代碼。我以爲我有這個使用字典,但作爲測試說我需要在每個值中的傢俱子類實例內的列表。任何有識之士將是巨大的

+0

'結果[傢俱空間] =(結果[傢俱空間],傢俱)'不符合你的要求。 – Blckknght

回答

2

測試期待,其結果將是這樣的:

mapping == {'Bedroom': [bed, table], 'Living Room': [sofa]} 

而創建:

{'Bedroom': (bed, table), 'Living Room': sofa} 

備註"Living Room"的值不是容器,而是單個的Sofa實例。

事實上,如果你在一個房間裏有三件傢俱,例如在「臥室」,並稱一個Sofa

{'Bedroom': ((bed, table), sofa), 'Living Room': sofa} 

你會繼續嵌套更深。

最小的解決方法是:

if furniture.room in results:     
    results[furniture.room].append(furniture)  
else:  
    results[furniture.room] = [furniture] 

注意使用listtuple可以得到同樣的結果,既可以被索引(雖然你add(不append)到元組);我認爲這裏列表更適合,但是你使用元組不是錯誤的來源。

0
def map_the_home(home): 
    results = dict() 
    for furniture in home: 
     results.setdefault(furniture.room,[]).append(furniture) 
    return results 

讓我們通過它的僞

home = [Bed('Bedroom'), Sofa('Living Room'), Table('Bedroom')] 
map_the_home(home) 
results = dict() 
for each piece of furniture in the home: 
    append that piece of furniture to results[furniture.room] 
    if results[furniture.room] doesn't exist, make it an empty list then append 
return the results