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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#!/usr/bin/python
# Machine's readings given in puzzle text
readings = {
"children" : 3,
"cats" : 7,
"samoyeds" : 2,
"pomeranians" : 3,
"akitas" : 0,
"vizslas" : 0,
"goldfish" : 5,
"trees" : 3,
"cars" : 2,
"perfumes" : 1
}
def solve_partn(partn, lines):
# Parse input file into a list of dictionaries
aunts = []
for line in lines:
words = line.split(" ")
data = {}
for i in range(3):
key = words[2 + 2 * i].rstrip(":")
val = words[3 + 2 * i].rstrip(",")
data[key] = int(val)
aunts.append(data)
# Find the aunt who gave us the present
for i, a in enumerate(aunts):
is_target = True
for k in a.keys():
if partn == 1:
is_target &= a[k] == readings[k]
else: # partn == 2
if k == "cats" or k == "trees":
is_target &= a[k] > readings[k]
elif k == "pomeranians" or k == "goldfish":
is_target &= a[k] < readings[k]
else:
is_target &= a[k] == readings[k]
if is_target:
return i + 1
return -1 # Shouldn't happen
def main():
# Read properties of all Aunts Sue from input text file
with open("input.txt", "r") as f:
lines = f.read().splitlines()
print("Part 1 solution:", solve_partn(1, lines)) # 213 for me
print("Part 2 solution:", solve_partn(2, lines)) # 323 for me
if __name__ == "__main__":
main()
|