Python递归函数给出不同的错误或正确的输出

时间:2017-05-29 21:44:20

标签: python recursion

我正在编写一个程序来计算游戏因子的不同配方的比例(就像看起来一样懒惰)。对于它,我使用下面的代码递归计算每个项目的每个比率。

     df = df.loc[:, df.isnull().mean() < .7]

但是,有时当我运行此程序时,我收到错误:

"""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

为什么会这样,我该如何解决?

1 个答案:

答案 0 :(得分:2)

如评论中所述,您需要移除包含set的{​​{1}}:

None

可能会将其更改为空ingredients={None}

dict

当你访问空字典时,你需要做一些合理的事情,可能:

ingredients={}