TIL about maketrans and also corrected some 6am mistakes

This commit is contained in:
a 2020-12-05 06:22:09 -06:00
parent 5d12ef26be
commit 08aa79acaa
2 changed files with 56 additions and 0 deletions

31
05/05_refactored.py Normal file
View file

@ -0,0 +1,31 @@
def read_file():
with open("input.txt","r") as f:
return f.read().split('\n')
def id(seat):
"""
Translate to binary.
"""
return int(seat.translate(str.maketrans('FBLR', '0101')), 2)
def part1(seats):
"""
Find the highest seat ID.
"""
ids = sorted(map(id, seats))
return max(ids)
def part2(seats):
"""
Find your seat ID, which is missing.
"""
ids = sorted(map(id, seats))
return sum( range(min(ids), max(ids)+1) ) - sum(ids)
def main():
seats = read_file()
print(f'{part1(seats)=}')
print(f'{part2(seats)=}')
if __name__ == "__main__":
main()

25
05/05_translate.py Normal file
View file

@ -0,0 +1,25 @@
"""
Turns out int() accepts different bases than 10.
We can also translate a string using translate() and a table,
or maketrans(). #TIL
"""
with open("input.txt", "r") as f:
seats = f.read().split('\n')
def id(code):
trans = str.maketrans('FBLR', '0101')
return int(code.translate(trans), 2) # it's literally just binary lmao -- x8 just means x1000 so shift 3 places, and there are 3 digits in the colpart
ids = [id(seat) for seat in seats]
print(f"Part 1: {max(ids)}") # i forgot that max() existed whoops
"""
Also, instead of iterating over the entire list of IDs,
we can find the missing seat by simply summing them.
The missing seat will be excluded from the total.
"""
expected_total = sum( range(min(ids), max(ids)+1) ) # some seats are missing
actual_total = sum(ids)
print(f"Part 2: {expected_total - actual_total}")