-
Notifications
You must be signed in to change notification settings - Fork 0
/
day4.py
76 lines (65 loc) · 1.58 KB
/
day4.py
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
67
68
69
70
71
72
73
74
75
# day4.py
testlines = """2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8""".splitlines()
with open('day4.txt') as fp:
data = fp.read().splitlines()
def parse_line(line):
lf, rt = line.split(',')
lfmin, lfmax = lf.split('-')
rtmin, rtmax = rt.split('-')
return (int(lfmin), int(lfmax)), (int(rtmin), int(rtmax))
def is_wholly_contained(a, b):
amin, amax = a
bmin, bmax = b
if amin < bmin:
# a starts to the left of b
if amax >= bmax:
return True
elif amin == bmin:
# starts in the same place, so one of them _must_ contain the other
return True
else:
# b starts to the left of a
if bmax >= amax:
return True
return False
def part1(lines):
num = 0
for line in lines:
a, b = parse_line(line)
if is_wholly_contained(a, b):
num += 1
return num
if __name__ == '__main__':
print('Part 1')
print('test: ', part1(testlines))
print('data: ', part1(data))
def is_overlapped(a, b):
amin, amax = a
bmin, bmax = b
if amin == bmin:
return True
elif amin < bmin:
# a starts to the left of b
if amax >= bmin:
return True
else:
# b starts to the left of a
if bmax >= amin:
return True
return False
def part2(lines):
num = 0
for line in lines:
a, b = parse_line(line)
if is_overlapped(a, b):
num += 1
return num
if __name__ == '__main__':
print('Part 2')
print('test: ', part2(testlines))
print('data: ', part2(data))