1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
#!/usr/bin/python
import json
def solve_partn(partn, data):
# Primitive data types
if isinstance(data, int) or isinstance(data, float):
return data
elif isinstance(data, str):
return 0
# Composite data types
result = 0
if isinstance(data, list):
for d in data:
result += solve_partn(partn, d)
elif isinstance(data, dict):
for d in data.values():
# Part 2: skip all objects containing "red" as value
if partn == 2 and isinstance(d, str) and d == "red":
return 0
else:
result += solve_partn(partn, d)
return result
def main():
# Read the JSON data from the input text file
with open("input.txt", "r") as f:
data = json.loads(f.read())
print("Part 1 solution:", solve_partn(1, data)) # 119433 for me
print("Part 2 solution:", solve_partn(2, data)) # 68466 for me
if __name__ == "__main__":
main()
|