Recursively reading Python data

The following will make more sense if you have ever played minecraft. Since many of you have not done this, I will try to explain it as best as possible.

I am trying to write a recursive function that can find the steps to create any minecraft element from a minecraft recipe flatfile. I have it very much.

The flat file is long, so I included it in this one .

def getRecipeChain(item, quantity=1):
    #magic recursive stuffs go here

So, basically, I need to look for the first recipe, and then look for recipes for all the components of this first recipe, and so on, until you get to items without recipes. Every time I need to add a recipe to the list, I get a kind of set of instructions on how to process objects.

So here is the function that I have (the one that doesn't work)

def getRecipeChain(name, quantity=1):
    chain = []

    def getRecipe(name1, quantity1=1):
        if name1 in recipes:
            for item in recipes[name1]["ingredients"]["input"]:
                if item in recipes:
                    getRecipe(item, quantity1)
                else:
                    chain.append(item)

    getRecipe(name, quantity)
    return chain

, . , .

>>> getRecipeChain("solar_panel", 1):
{"insulated_copper_cable":13, "electronic_circuit":2, "re_battery":1, "furnace":1, "machine":1, "generator":1, "solar_panel":1}

, , ?

, , , , , , , .

+5
2

collections.Counter, :

from collections import Counter

def getRecipe(name, quantity=1):
  if not name in recipes: return Counter({name: quantity})

  subitems = recipes[name]["ingredients"]["input"]
  return sum((getRecipe(item, quantity) for item in subitems), 
             Counter())

print repr(dict(getRecipe("solar_panel")))
# => {'copper': 39, 'refined_iron': 10, 'glass': 3, 
#     'rubber': 78, 'cobblestone': 8, 'tin': 4, 
#     'coal_dust': 3, 'nothing': 10, 'redstone': 6}
+3

, 2 . , getRecipe(). -, , . , . - - , . , , .

def getRecipe(name, quantity=1):
    chain=[];
    if name in recipes:
        for item in recipes[name]["ingredients"]["input"]:
            if item in recipes:
                chain.append(getRecipe(item, quantity))
            else:
                chain.append(item)
    return chain

EDIT: , .

from collections import Counter
def getRecipe(name, quantity=1, count=Counter()):
    if name in recipes:
        for item in recipes[name]["ingredients"]["input"]:
            if item in recipes:
                getRecipe(item, quantity,counter)
            else:
                counter[item]+=quantity
    return counter
+1

All Articles