import re rules = {} with open('input.txt') as fh: for line in fh: m = re.match('(.*) bags contain (.*)\.$', line.strip()) key = m[1] values = m[2] rules[key] = {} for value in values.split(', '): if value == 'no other bags': continue m = re.match('([0-9]+) (.*) bags?$', value) rules[key][m[2]] = int(m[1]) def find_containing(start): results = [] todo = [start] while todo: cur = todo.pop() for key, values in rules.items(): if cur in values and key not in results: results.append(key) todo.append(key) return results def count_contained(start): result = 0 for color, count in rules[start].items(): result += count * (count_contained(color) + 1) return result print(len(find_containing('shiny gold'))) print(count_contained('shiny gold'))