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
这是为什么,我该如何解决这个问题?
'成分= {None}'是一个只包含一个元素的'set','None'。你想创建一个空字典吗?使用'成分= {}'。 –
谢谢!代码现在工作正常。 –