/
day04.py
73 lines (56 loc) · 1.48 KB
/
day04.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
import common
log = common.get_logger(__name__)
def split_head(inlist):
while len(inlist) > 1:
head = inlist[0]
tail = inlist[1:]
yield head, tail
inlist = tail
def has_duplicates(s, delim=' '):
# type: (str) -> bool
tokens = s.split(delim)
for head, tail in split_head(tokens):
if head in tail:
return True
return False
def is_anagram(s1, s2):
l1 = list(s1)
l1 = sorted(l1)
l2 = list(s2)
l2 = sorted(l2)
return l1 == l2
def has_anagrams(s):
tokens = s.split(' ')
for head, tail in split_head(tokens):
for t in tail:
if is_anagram(head, t):
return True
return False
def is_valid(s):
# type: (str) -> bool
if not s:
return False
if has_duplicates(s):
return False
if has_anagrams(s):
return False
return True
def parse_input(intext):
return intext.split('\n')
def main():
passphrases = parse_input(common.read_input(4))
answer_1 = 0
answer_2 = 0
idx = 1
for p in passphrases:
log.debug('Testing passphrase ({}/{})'.format(idx, len(passphrases)))
idx += 1
if not has_duplicates(p):
answer_1 += 1
if not has_anagrams(p):
answer_2 += 1
print('The answer to part 1 is: {}'.format(answer_1))
print('The answer to part 2 is: {}'.format(answer_2))
if __name__ == '__main__':
log = common.get_logger('day04', level='INFO')
main()