Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用递归查找原始成分的计数_Python_Recursion - Fatal编程技术网

在Python中使用递归查找原始成分的计数

在Python中使用递归查找原始成分的计数,python,recursion,Python,Recursion,我们得到了一本食谱词典,以及原料清单 recipes = { 'axe': {'stick': 1, 'rock': 1, 'tape': 1}, 'double_axe': {'axe': 2, 'tape': 1}, 'quadruple_axe': {'double_axe': 2, 'tape': 1, 'rock': 2} } raw_ingredients = {'rock', 'stick', 'tape'} 问题是,;以编程方式查找每个配方使用的(每种类型)原料数量。请注意,

我们得到了一本食谱词典,以及原料清单

recipes = {
'axe': {'stick': 1, 'rock': 1, 'tape': 1},
'double_axe': {'axe': 2, 'tape': 1},
'quadruple_axe': {'double_axe': 2, 'tape': 1, 'rock': 2}
}

raw_ingredients = {'rock', 'stick', 'tape'}
问题是,;以编程方式查找每个配方使用的(每种类型)原料数量。请注意,原料仅包括
岩石
胶带
、和

下面是我用Python解决这个问题的尝试

def get_ingredients(name, s, l):
s[name]=dict1
#get dictionary for each recipe

k=dict1.keys()
#retrieve the keys
dict2={}
#define empty dictionary to store count of raw ingredients
for i in k:
 #loop over the keys   
    if i in l:
 #if key is a raw ingredient, we will increase the count for that corresponding raw ingredient
        dict2[i]=dict1[i]
    else:
#otherwise call the function recursively
        for j in range(0,dict1[i]):
        get_ingredients(i, s, l)
这里的
name
可以是
{axe,double\u-axe,quartle\u-axe}
s
recipes
相同,
l
原料相同

我完全理解,我的代码不完整。这只是我对这个问题的第一次尝试,我想在这里了解一下基本情况。以下是我需要帮助的两个关键问题

  • 首先,如何记录所需配料的数量,例如,总共需要4根棍子
  • 第二,我们什么时候停止递归,即这里的基本情况是什么

  • 提前感谢您的帮助

    您的基本情况是配料名称未显示为配方标签。 在三种
    类型上重复出现;您可以在
    棍子
    岩石
    磁带
    上停车

    你可以通过传回基本成分的数量来跟踪。例如,检查“双轴”将返回
    2*{'stick':1,'rock':1,'tape':1}+{'tape':1}
    的计算汇总。您应该能够自己派生该代码,或者在这里使用类似“Python添加两个dict值”的内容来查找它

    首先,如何记录所需配料的数量,例如 实例四联斧总共需要4根棍子

    你使用字典收集配料数量的本能是好的:

    dict2={}
    #define empty dictionary to store count of raw ingredients
    
    但是,请把评论放在它评论的那一行之前,而不是后面

    第二,我们什么时候停止递归,即这里的基本情况是什么

    你直接处理原料,你重复子配方。因此,当你用尽所有的子配方时,复发自然停止——你不必显式地测试它

    我建议您停止思考
    dict1
    dict2
    以及
    I
    j
    k
    以及问题语言的程序。我还建议您使用
    defaultdict
    收集您的最终原料列表,如果您觉得需要,在最后将其转换为通用
    dict
    。但这是可选的,只是简化了代码:

    from collections import defaultdict
    
    recipes = {
        'axe': {'stick': 1, 'rock': 1, 'tape': 1},
        'double_axe': {'axe': 2, 'tape': 1},
        'quadruple_axe': {'double_axe': 2, 'tape': 1, 'rock': 2}
    }
    
    raw_ingredients = {'rock', 'stick', 'tape'}
    
    def count_raw_ingredients(recipe):
        ingredients = defaultdict(int)
    
        for ingredient, amount in recipes[recipe].items():
            if ingredient in raw_ingredients:
                ingredients[ingredient] += amount
            else:
                for subingredient, subamount in count_raw_ingredients(ingredient).items():
                    ingredients[subingredient] += amount * subamount
    
        return dict(ingredients)
    
    print(count_raw_ingredients('quadruple_axe'))
    
    输出

    > python3 test.py
    {'stick': 4, 'rock': 6, 'tape': 7}
    >
    

    请不要注释“same as”变量,并期望我们用我们阅读的每一行进行翻译。取而代之的是,给变量起一个清晰、有意义的名字。看起来代码的缩进被破坏了。@cdlane。谢谢你的回复。我只有一个问题;在
    成分[subcomponent]+=amount*subamount
    行中,我们真的需要进行就地增加吗。如果我们进行就地增加,可能会发生双斧的棍棒数量可以达到(1+(2*1))=3。所以,做一个简单的替换,
    成分[子成分]=amount*submount
    ,不是更好吗。你能解释一下为什么我们需要在这里进行适当的增加吗?thanks@jayant,你可以试着去看,但我相信这最终会导致错误的答案。通过查看子配方得到的原材料与当前配方中列出的原材料无关,因此我们始终需要添加。