advent/2020/4/solution.py

139 lines
3.0 KiB
Python
Raw Permalink Normal View History

2021-07-20 12:54:35 -05:00
#!/usr/bin/python
import re
class Passport:
def __init__(self):
self.info = {
"byr": "",
"iyr": "",
"eyr": "",
"hgt": "",
"hcl": "",
"ecl": "",
"pid": "",
"cid": "",
}
def set(self, info, data):
self.info[info] = data
def exist(self, info):
return not self.info[info] == ""
def ret(self, info):
return self.info[info]
def reader(line):
p = Passport()
spaced = line.split(' ')
for i in spaced:
pairs = i.split(':')
p.set(pairs[0], pairs[1])
return p
def alphasplit(s):
return (''.join(filter(str.isdigit, s)) or None,
''.join(filter(str.isalpha, s)) or None)
def color(line):
if not line[0] == "#": return False
if not len(line) == 7: return False
line.lower()
gcnt = 0
for i in line[1:]:
cnt = 0
for j in [c for c in 'abcdef1234567890']:
if i == j: cnt += 1
if cnt > 1: gcnt += 1
if not gcnt == 7: return False
return True
def mcolor(line):
if not line[0] == "#": return False
if not len(line) == 7: return False
acceptable = [c for c in 'abcdef1234567890']
line = line.lower().rstrip()
m = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', line)
if not m: return False
return True
def s_verify(p):
if p.exist('byr') and \
p.exist('iyr') and \
p.exist('eyr') and \
p.exist('hgt') and \
p.exist('hcl') and \
p.exist('ecl') and \
p.exist('pid'): return True
return False
def c_verify(p):
if not s_verify(p): return False
for i in ['byr', 'iyr', 'eyr']:
if not len(p.ret(i)) == 4: return False
if int(p.ret('byr')) >= 1920 and \
int(p.ret('byr')) <= 2002: pass
else:
return False
if int(p.ret('iyr')) >= 2010 and \
int(p.ret('iyr')) <= 2020: pass
else:
return False
if int(p.ret('eyr')) >= 2020 and \
int(p.ret('eyr')) <= 2030: pass
else:
return False
spl = alphasplit(p.ret('hgt'))
units = spl[1]
if units == None:
return False
num = spl[0]
if units == "cm":
if int(num) >= 150 and int(num) <= 193: pass
else: return False
elif units == "in":
if int(num) >= 59 and int(num) <= 76: pass
else: return False
else:
return False
if not mcolor(p.ret('hcl')): return False
if not p.ret('ecl') in 'amb blu brn gry grn hzl oth'.split(' '): return False
if not len(p.ret('pid')) == 9: return False
return True
fd = open('input', 'r')
lines = fd.readlines()
buf = [""]
for i in lines:
i = i.rstrip()
if len(i) == 0:
buf.append("")
continue
if buf[-1] == "":
buf[-1] = i
else:
buf[-1] += " "
buf[-1] += i
passports = []
for i in buf:
passports.append(reader(i))
cnt = 0
for i in passports:
if s_verify(i): cnt += 1
print(cnt)
cnt = 0
for i in passports:
if c_verify(i): cnt += 1
print(cnt)