5

Minecraftをプレイしたことがある場合は、次の方が理にかなっています。まだまだ多くの方がいらっしゃるので、できる限り説明させていただきます。

MinecraftレシピのフラットファイルからMinecraftアイテムを作成する手順を見つけることができる再帰関数を作成しようとしています。これは本当に困惑しています。

フラットファイルはちょっと長いので、この要点に含めました。

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

したがって、基本的には、最初のレシピを調べてから、その最初のレシピのすべてのコンポーネントのレシピを調べて、レシピのないアイテムに到達するまで続けます。レシピをリストに追加する必要があるたびに、アイテムを作成する順序の一種の命令セットを取得します。

だからここに私が今持っている機能があります(それは機能しません)

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}

だから問題は、どうすればいいのかということです。

私は人々にあなたのために仕事をするように頼むことはここで眉をひそめていることを知っています、それであなたがこれが私のためにコーディングをしているだけであなたに少し近すぎると感じるなら、ちょうどそう言ってください。

4

2 に答える 2

3

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}
于 2012-03-07T00:29:22.443 に答える
1

問題は2つあると思います。まず、getRecipe()の再帰呼び出しで、チェーンにアイテムを追加する必要があります。第二に、2つの機能が不必要に物事を複雑にしていると思います。私は内側のものだけがすべきだと思います。このようなものがあなたが探しているものです。私はそれをテストしていませんが、あなたが正しい軌道に乗るのに十分近いはずです。

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

編集:コメントは私のPython知識の欠如を埋めているので、ここにもっと良い解決策があります。

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
于 2012-03-07T00:18:38.327 に答える