0
私は、ゲームFactorio(これは怠け者だと思われます)のさまざまなレシピの比率を計算するプログラムを作成しています。そのためには、以下のコードを使用して、各アイテムの各比率を再帰的に計算します。異なるエラーや正しい出力を与えるPythonの再帰関数
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
なぜこれがあると、私はこれをどのように修正することができますが、私はこのプログラムを実行するときしかし、時々私はエラーを取得する
"""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))
?あなたがNone
を含むset
を削除する必要がありますコメントで述べたように
' ingredients = {None} 'はただ一つの要素' None'を含む 'set'です。空のDICTを作成したいですか? 'ingredients = {}'を使ってください。 –
ありがとう!コードは正常に動作します。 –