我正在尝试解决 Code 2020 第 7 天来临的第二部分。
我创建了一个嵌套字典,显示袋子中的袋子,我想遍历嵌套的字典并取值的乘积。该值表示父袋子可以容纳的袋子数量,因此我需要计算嵌套字典中容纳的袋子总数。
有什么关于如何做到这一点的建议吗?
完整数据集:https://pastebin.com/Xi9UY9e2
来自代码出现的说明
faded blue bags contain 0 other bags.
dotted black bags contain 0 other bags.
vibrant plum bags contain 11 other bags: 5 faded blue bags and 6 dotted black bags.
dark olive bags contain 7 other bags: 3 faded blue bags and 4 dotted black bags.
因此,一个闪亮的金色袋子必须包含 1 个深橄榄色袋子(以及其中的 7 个袋子)和 2 个充满活力的李子袋子(以及每个袋子中的 11 个袋子):1 + 17 + 2 + 211 = 32 袋!
这是我迄今为止用来生成字典的内容
import re
from nested_lookup import nested_lookup
from nested_lookup import nested_update
data = my_file.readlines()
rulesList = []
parentBags = []
for count, rules in enumerate(data):
match = re.match(r"(.*) bags contain (.*).", rules)
if match is not None:
key = match.group(1)
contents = re.findall(r"(\d+) (\w+ \w+)", str(match.group(2)))
rulesList.append([key, contents])
else:
print("no match:", rules, end="")
def getBagColours(bag, bags):
tempPath = []
global total
for rule in bags:
for r in rule[1]:
if bag in r[1]:
tempPath.append(rule[0])
if len(tempPath) > 0:
for x in tempPath:
if x not in parentBags:
parentBags.append(x)
for bag in tempPath:
getBagColours(bag, bags)
else:
return
getBagColours("shiny gold", rulesList)
print("The number of bags that can contain shiny gold bags is", len(parentBags))
##### Part Two #####
print("\nPart Two\n")
total = 0
tree = {}
def getBagSum(bag, bags):
global tree
bagsToCheck = []
for rule in bags:
if bag == rule[0]:
for r in rule[1]:
bagsToCheck.append(r[1])
x = dict({r[1]:{"value":r[0]}})
if len(str(nested_lookup(bag, tree))) > 4:
x = x | nested_lookup(bag, tree)[0]
nested_update(tree, key=bag, value=x, in_place=True)
if len(bagsToCheck) > 0:
for bag in bagsToCheck:
getBagSum(bag, bags)
else:
return
for rule in rulesList:
if rule[0] == "shiny gold":
goldenBag = rule
for b in goldenBag[1]:
tree[b[1]] = {"value":b[0]}
getBagSum(b[1], rulesList)