[英]Python recursive function giving different error or correct output
我正在编写一个程序,计算出游戏Factorio的不同配方的比例(看起来很懒)。 为此,我使用下面的代码递归计算出每个项目的每个比率。
"""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
:
ingredients={None}
并可能将其更改为空dict
:
ingredients={}
另外,访问空字典时,您将需要做一些合理的事情,也许是:
items[item][1].get(ingredient, 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.