-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdayFour.py
110 lines (86 loc) · 2.59 KB
/
dayFour.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# q1
values = []
with open("dayFour.txt") as file:
for line in file:
values.append(line.rstrip())
parsed_values = []
temp = []
i = 0
while i < len(values):
if values[i] != '':
temp.append(" " + values[i])
else:
parsed_values.append("".join(temp))
temp = []
i += 1
# append last temp
parsed_values.append("".join(temp))
def isValid(value, credentials):
count = 0
for credential in credentials:
if credential in value:
count += 1
return count == len(credentials)
res = 0
must_haves = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
for value in parsed_values:
if isValid(value, must_haves):
res += 1
print(f"result: {res}")
# q2
import re
credential_specifications = {
"byr": [1920, 2002],
"iyr": [2010, 2020],
"eyr": [2020, 2030],
"in" : [59, 76],
"cm" : [150, 193],
"ecl": ["amb", "blu", "brn", "gry", "hzl", "oth", "grn"],
}
def checkAPair(cred, val, keymap):
pattern = (r'#[a-f0-9]{6}')
if cred == "hgt":
if "in" in val:
num = int(val.replace("in", ""))
return keymap["in"][0] <= num and keymap["in"][1] >= num
elif "cm" in val:
num = int(val.replace("cm", ""))
return keymap["cm"][0] <= num and keymap["cm"][1] >= num
elif cred == "hcl":
if len(val) == 7:
match = re.search(pattern, val)
if match:
return True
elif cred == "ecl":
return val in keymap["ecl"]
elif cred == "pid":
if len(val) == 9:
count = 0
for s in val:
n = int(s)
if n >= 0 or n <= 9:
count += 1
return len(val) == count
else:
min_value = keymap[cred][0]
max_value = keymap[cred][1]
return int(val) >= min_value and int(val) <= max_value
return False
def checkIfValid(keymap, value, credentials):
value = value.split()
for i in range(len(value)):
value[i] = str(value[i]).split(":")
pairs = {x:y for x,y in value}
for cred in credentials:
val = pairs[cred]
if not checkAPair(cred, val, keymap):
return False
return True
valid = 0
for value in parsed_values:
if isValid(value, must_haves):
if checkIfValid(credential_specifications, value, must_haves):
# print(value)
# print()
valid += 1
print(f"Number of valid passports are: {valid}")