2017-05-29 43 views
0

我正在編寫一個程序,計算遊戲Factorio的不同食譜的比率(就像看起來那麼懶)。對於它,我使用下面的代碼遞歸地計算每個項目的每個比率。Python遞歸函數給出不同的錯誤或正確的輸出

"""Imports""" 
from collections import namedtuple, defaultdict 

# Item is a named tuple called Item which expects two attributes, craft time and ingredients 

Item = namedtuple('Item', ['craft_time', 'ingredients']) 

# A dictionary of all the different items to be crafted 

items = {'iron gear wheel': Item(craft_time=0.5, ingredients={None}), 
     'copper cable': Item(craft_time=0.5, ingredients={None}), 
     'transport belt': Item(craft_time=0.5, ingredients={'iron gear wheel': 1}), 
     'fast transport belt': Item(craft_time=0.5, ingredients={'iron gear wheel': 5, 'transport belt': 1})} 


# Functions 

def find_ratio(item, rate_of_production): 
    """ 
    This recursive function finds the ratio of factories needed to produce the item at the rate of production. 
    """ 

    # creates a default dict object 
    dict_of_ratios = defaultdict(list) 

    # adds the ratio of the item itself to the dict of ratios 
    dict_of_ratios[item].append(rate_of_production/items[item][0]) 

    # iterate through the rest of the ingredients of the item 
    for ingredient in iter(items[item][1]): 

     # if there are no ingredients 
     if ingredient is None: 
      break 

     # iterate through the returned dict from find ratio and add them to the currently running dict of ratios 
     print(item) 
     for item, ratio in iter(find_ratio(ingredient, items[item][1] [ingredient] * rate_of_production).items()): 
      dict_of_ratios[item].append(ratio) 

# iterate through dict of ratios and sum all of the values 
for item in iter(dict_of_ratios.keys()): 
    dict_of_ratios[item] = sum(dict_of_ratios[item]) 

    return dict_of_ratios 


found_ratio = find_ratio("fast transport belt", 2) 

# print the resulting ratio 
print('You will need:') 
for i in found_ratio: 
    print("\t{} {} factories".format(found_ratio[i], i)) 

但是,有時,當我運行這個程序,我得到的錯誤:預期的結果

Traceback (most recent call last): 
fast transport belt 
    File "E:/Will/William's Projects/Code/Tests/FactrioRatios.py", line 52, in <module> 
iron gear wheel 
found_ratio = find_ratio("fast transport belt", 2) 
    File "E:/Will/William's Projects/Code/Tests/FactrioRatios.py", line 41, in find_ratio 
for item, ratio in iter(find_ratio(ingredient, items[item][1][ingredient] * 
rate_of_production).items()): 
TypeError: 'set' object is not subscriptable 

等次:

You will need: 
    4.0 fast transport belt factories 
    4.0 transport belt factories 
    8.0 iron gear wheel factories 

這是爲什麼,我該如何解決這個問題?

+2

'成分= {None}'是一個只包含一個元素的'set','None'。你想創建一個空字典嗎?使用'成分= {}'。 –

+0

謝謝!代碼現在工作正常。 –

回答

2

正如評論指出的,你將需要刪除包含setNone

ingredients={None} 

,並有可能將其更改爲空dict

ingredients={} 

你也需要做一些合理的行爲時您訪問空字典,也許:

items[item][1].get(ingredient, 0)