gpt4 book ai didi

Python 递归读取数据

转载 作者:太空狗 更新时间:2023-10-30 01:16:55 25 4
gpt4 key购买 nike

如果你玩过我的世界,下面的内容会更有意义。由于你们中的许多人还没有,我会尽力解释一下

我正在尝试编写一个递归函数,它可以找到从 Minecraft 配方平面文件中制作任何 Minecraft 元素的步骤。这个真的让我难住了。

平面文件有点长,所以我将其包含在 this 中要点。

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}

那么问题是,我该怎么做呢?

我知道要求别人为你工作在这里是不受欢迎的,所以如果你觉得这有点太接近你只是为我编写代码,那就直说吧。

最佳答案

这可以使用 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}

关于Python 递归读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9593901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com