finished day 1
This commit is contained in:
parent
fdbc386511
commit
db4717556e
31
day1/day1.py
31
day1/day1.py
|
@ -6,18 +6,42 @@ import sys
|
|||
|
||||
def parse(puzzle_input):
|
||||
"""Parse input"""
|
||||
return [int(string) for string in puzzle_input.splitlines()]
|
||||
|
||||
def part1(data):
|
||||
def part1(data:list[int]):
|
||||
"""Solve part 1"""
|
||||
data.sort()
|
||||
while True:
|
||||
if len(data)<2:
|
||||
raise ValueError('no match found')
|
||||
s = data[0]+data[-1]
|
||||
if s>2020:
|
||||
data.pop(-1)
|
||||
elif s<2020:
|
||||
data.pop(0)
|
||||
else:
|
||||
return data[0]*data[-1]
|
||||
|
||||
def part2(data):
|
||||
"""Solve part 2"""
|
||||
data.sort()
|
||||
while True:
|
||||
if len(data)<3:
|
||||
raise ValueError('no match found')
|
||||
if data[0]+data[1]+data[-1]>2020:
|
||||
data.pop(-1)
|
||||
elif data[0]+data[-1]+data[-2]<2020:
|
||||
data.pop(0)
|
||||
elif data[0]+data[1]+data[-1]==2020:
|
||||
return data[0]*data[1]*data[-1]
|
||||
else:
|
||||
return data[0]*data[-1]*data[-2]
|
||||
|
||||
def solve(puzzle_input):
|
||||
"""Solve the puzzle for the given input"""
|
||||
data = parse(puzzle_input)
|
||||
solution1 = part1(data)
|
||||
solution2 = part2(data)
|
||||
solution1 = part1(data.copy())
|
||||
solution2 = part2(data.copy())
|
||||
|
||||
return solution1, solution2
|
||||
|
||||
|
@ -25,6 +49,5 @@ if __name__ == "__main__":
|
|||
for path in sys.argv[1:]:
|
||||
print(f"{path}:")
|
||||
puzzle_input = pathlib.Path(path).read_text().strip()
|
||||
print(f'{puzzle_input}')
|
||||
solutions = solve(puzzle_input)
|
||||
print("\n".join(str(solution) for solution in solutions))
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import pathlib
|
||||
import pytest
|
||||
import template as aoc
|
||||
import day1 as aoc
|
||||
|
||||
PUZZLE_DIR = pathlib.Path(__file__).parent
|
||||
|
||||
|
@ -17,17 +17,17 @@ def example2():
|
|||
puzzle_input = (PUZZLE_DIR / "example2").read_text().strip()
|
||||
return aoc.parse(puzzle_input)
|
||||
|
||||
@pytest.mark.skip(reason="Not implemented")
|
||||
# @pytest.mark.skip(reason="Not implemented")
|
||||
def test_parse_example1(example1):
|
||||
"""Test that input is parsed properly"""
|
||||
assert example1 == ...
|
||||
assert example1 == [1721, 979, 366, 299, 675, 1456]
|
||||
|
||||
@pytest.mark.skip(reason="Not implemented")
|
||||
# @pytest.mark.skip(reason="Not implemented")
|
||||
def test_part1_example1(example1):
|
||||
"""Test part 1 on example input"""
|
||||
assert aoc.part1(example1) == ...
|
||||
assert aoc.part1(example1) == 514579
|
||||
|
||||
@pytest.mark.skip(reason="Not implemented")
|
||||
def test_part2_example2(example2):
|
||||
# @pytest.mark.skip(reason="Not implemented")
|
||||
def test_part2_example2(example1):
|
||||
"""Test part 2 on example input"""
|
||||
assert aoc.part2(example2) == ...
|
||||
assert aoc.part2(example1) == 241861950
|
||||
|
|
Loading…
Reference in a new issue