diff --git a/adventofcode/2015/day15/day15.py b/adventofcode/2015/day15/day15.py index dd708d7..238861e 100644 --- a/adventofcode/2015/day15/day15.py +++ b/adventofcode/2015/day15/day15.py @@ -27,12 +27,12 @@ def example(ingredients): # for example input, two ingredients such that # a + b = 100 with a and b >= 0 max_score = 0 - for a in range(0, 101): + for a in range(101): b = 100 - a # ignore last property (calories) qty_a = [x * a for x in ingredients[0][:-1]] qty_b = [x * b for x in ingredients[1][:-1]] - props = [x + y if x + y > 0 else 0 for x, y in zip(qty_a, qty_b)] + props = [max(0, x + y) for x, y in zip(qty_a, qty_b)] score = reduce(mul, props) max_score = max(score, max_score) return max_score @@ -40,14 +40,14 @@ def example(ingredients): def example_part2(ingredients): max_score = 0 - for a in range(0, 101): + for a in range(101): b = 100 - a qty_a = [x * a for x in ingredients[0]] qty_b = [x * b for x in ingredients[1]] # check calories == 500 if qty_a[-1] + qty_b[-1] != 500: continue - props = [x + y if x + y > 0 else 0 for x, y in zip(qty_a, qty_b)] + props = [max(0, x + y) for x, y in zip(qty_a, qty_b)] score = reduce(mul, props[:-1]) max_score = max(score, max_score) return max_score @@ -61,7 +61,7 @@ def part1(ingredients): qty_c = [x * c for x in ingredients[2][:-1]] qty_d = [x * d for x in ingredients[3][:-1]] props = [ - x + y + z + w if x + y + z + w > 0 else 0 + max(0, x + y + z + w) for x, y, z, w in zip(qty_a, qty_b, qty_c, qty_d) ] score = reduce(mul, props) @@ -77,7 +77,7 @@ def part2(ingredients): qty_c = [x * c for x in ingredients[2]] qty_d = [x * d for x in ingredients[3]] props = [ - x + y + z + w if x + y + z + w > 0 else 0 + max(0, x + y + z + w) for x, y, z, w in zip(qty_a, qty_b, qty_c, qty_d) ] # check calories == 500 diff --git a/adventofcode/2018/day2/day2.py b/adventofcode/2018/day2/day2.py index f9c06f1..680b6c2 100644 --- a/adventofcode/2018/day2/day2.py +++ b/adventofcode/2018/day2/day2.py @@ -17,7 +17,7 @@ def main(lines): c = Counter(line) total_twice += 1 if [k for k,v in c.items() if v == 2] != [] else 0 total_thrice += 1 if [k for k,v in c.items() if v == 3] != [] else 0 - print(f"Part 1: ", total_twice * total_thrice) + print("Part 1: ", total_twice * total_thrice) part2(lines) @@ -26,5 +26,5 @@ if __name__ == "__main__": import sys infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt" with open(infile) as inp: - main([l.rstrip() for l in inp.readlines()]) + main([l.rstrip() for l in inp]) diff --git a/adventofcode/2018/day3/day3.py b/adventofcode/2018/day3/day3.py index 9989418..a500404 100644 --- a/adventofcode/2018/day3/day3.py +++ b/adventofcode/2018/day3/day3.py @@ -1,8 +1,7 @@ #!/usr/bin/env python3 import re -import itertools -from dataclasses import dataclass from collections import defaultdict +from dataclasses import dataclass @dataclass @@ -35,7 +34,7 @@ def main(inp): regions[x, y].add(id_) total = sum(len(x) > 1 for x in regions.values()) - print(f"Part 1: ", total) + print("Part 1: ", total) all_ids = set() overlapping_ids = set() @@ -51,5 +50,5 @@ if __name__ == '__main__': import sys infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt" with open(infile) as inp: - main([l.rstrip() for l in inp.readlines()]) + main([l.rstrip() for l in inp]) diff --git a/adventofcode/2018/day4/day4.py b/adventofcode/2018/day4/day4.py index e6aded4..67e0d46 100644 --- a/adventofcode/2018/day4/day4.py +++ b/adventofcode/2018/day4/day4.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import re -from collections import defaultdict, Counter -from pprint import pprint +from collections import defaultdict def main(inp): diff --git a/adventofcode/2018/day6/day6.py b/adventofcode/2018/day6/day6.py index 5c30051..309390c 100644 --- a/adventofcode/2018/day6/day6.py +++ b/adventofcode/2018/day6/day6.py @@ -1,6 +1,5 @@ from collections import defaultdict, namedtuple - Point = namedtuple('Point', ['x', 'y']) diff --git a/adventofcode/2018/day7/day7.py b/adventofcode/2018/day7/day7.py index add624e..2c83323 100644 --- a/adventofcode/2018/day7/day7.py +++ b/adventofcode/2018/day7/day7.py @@ -84,5 +84,5 @@ if __name__ == '__main__': import sys infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt" with open(infile) as inp: - main([l.rstrip() for l in inp.readlines()]) + main([l.rstrip() for l in inp]) diff --git a/adventofcode/2019/day1/day1.py b/adventofcode/2019/day1/day1.py index 057a266..59672a2 100644 --- a/adventofcode/2019/day1/day1.py +++ b/adventofcode/2019/day1/day1.py @@ -25,9 +25,7 @@ def test_part2(): expected = (2, 966, 50346) for i, inp in enumerate(inputs): result = calculate_fuel_iterative(inp) - assert result == expected[i], "Result for {} should be {}, was {}".format( - inp, expected[i], result - ) + assert result == expected[i], f"Result for {inp} should be {expected[i]}, was {result}" print("All tests passed for part 2.") diff --git a/adventofcode/2019/day10/day10.py b/adventofcode/2019/day10/day10.py index 89fc6a5..1aac976 100644 --- a/adventofcode/2019/day10/day10.py +++ b/adventofcode/2019/day10/day10.py @@ -1,9 +1,8 @@ -import time -import math import cmath -from itertools import combinations -from collections import defaultdict +import math from bisect import insort +from collections import defaultdict +from itertools import combinations def dist(a, b): diff --git a/adventofcode/2019/day11/day11.py b/adventofcode/2019/day11/day11.py index cdee7f8..bbac6b7 100644 --- a/adventofcode/2019/day11/day11.py +++ b/adventofcode/2019/day11/day11.py @@ -1,4 +1,4 @@ -from adventofcode.intcode import interpret_intcode, Interpreter +from adventofcode.intcode import Interpreter def paint(program, initial_state): diff --git a/adventofcode/2019/day13/day13.py b/adventofcode/2019/day13/day13.py index c2206ef..90228db 100644 --- a/adventofcode/2019/day13/day13.py +++ b/adventofcode/2019/day13/day13.py @@ -39,7 +39,7 @@ def parse_map(output): grid[x, y] = tile paddle = next((k for k, v in grid.items() if v == 3), None) ball = next((k for k, v in grid.items() if v == 4), None) - bounds = (max(x for x, y in grid.keys()), max(y for x, y in grid.keys())) + bounds = (max(x for x, y in grid), max(y for x, y in grid)) return grid, bounds, score, paddle, ball diff --git a/adventofcode/2019/day3/day3.py b/adventofcode/2019/day3/day3.py index 220e2be..b3bc284 100644 --- a/adventofcode/2019/day3/day3.py +++ b/adventofcode/2019/day3/day3.py @@ -54,9 +54,7 @@ def tests(): expected = (6, 159, 135) for i, inp in enumerate(inputs): result = find_min_distance(inp[0], inp[1]) - assert result == expected[i], "Result for {} should be {}, was {}".format( - inp, expected[i], result - ) + assert result == expected[i], f"Result for {inp} should be {expected[i]}, was {result}" # Part 2 # expected number of steps @@ -64,9 +62,7 @@ def tests(): print("All tests passed.") for i, inp in enumerate(inputs): result = find_least_steps(inp[0], inp[1]) - assert result == expected_part2[i], "Result for {} should be {}, was {}".format( - inp, expected_part2[i], result - ) + assert result == expected_part2[i], f"Result for {inp} should be {expected_part2[i]}, was {result}" if __name__ == "__main__": tests() diff --git a/adventofcode/2019/day5/day5.py b/adventofcode/2019/day5/day5.py index a15a6cd..24a1855 100644 --- a/adventofcode/2019/day5/day5.py +++ b/adventofcode/2019/day5/day5.py @@ -1,9 +1,8 @@ #! /usr/bin/env python3 -from collections import namedtuple -from enum import Enum import logging +from enum import Enum -logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.WARN) +logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.WARNING) def get_nth_digit(n, number): diff --git a/adventofcode/2019/day5/day52.py b/adventofcode/2019/day5/day52.py index d31af56..51b012b 100644 --- a/adventofcode/2019/day5/day52.py +++ b/adventofcode/2019/day5/day52.py @@ -93,7 +93,6 @@ class HaltInstruction(Instruction): def execute(self, intcode, arguments): intcode.halted = True - return None class Argument: diff --git a/adventofcode/2019/day6/day6.py b/adventofcode/2019/day6/day6.py index cebeeb7..014067c 100644 --- a/adventofcode/2019/day6/day6.py +++ b/adventofcode/2019/day6/day6.py @@ -1,4 +1,3 @@ -from collections import defaultdict def path(graph, start, goal): diff --git a/adventofcode/2019/day7/day7.py b/adventofcode/2019/day7/day7.py index 4e29b8c..6e0cb8f 100644 --- a/adventofcode/2019/day7/day7.py +++ b/adventofcode/2019/day7/day7.py @@ -1,7 +1,7 @@ -import sys -from pathlib import Path from itertools import cycle, permutations -from adventofcode.intcode import interpret_intcode, Interpreter + +from adventofcode.intcode import Interpreter, interpret_intcode + def main(inp): mem = list(map(int, inp.readline().rstrip().split(","))) diff --git a/adventofcode/2020/day11/rules.py b/adventofcode/2020/day11/rules.py index df65fca..2314aa3 100644 --- a/adventofcode/2020/day11/rules.py +++ b/adventofcode/2020/day11/rules.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -from itertools import count, takewhile +from itertools import takewhile directions = ( (-1, -1), diff --git a/adventofcode/2020/day15/day15.py b/adventofcode/2020/day15/day15.py index 69e4fcf..d515e8f 100644 --- a/adventofcode/2020/day15/day15.py +++ b/adventofcode/2020/day15/day15.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -from collections import defaultdict from array import array +from collections import defaultdict def main(initial_suite, max_iteration): diff --git a/adventofcode/2020/day4/day4.py b/adventofcode/2020/day4/day4.py index f2c7be6..e73a44d 100644 --- a/adventofcode/2020/day4/day4.py +++ b/adventofcode/2020/day4/day4.py @@ -29,9 +29,7 @@ def check_passeport(passeport, run_validators=False): ] for field, validator in fields: value = passeport.get(field) - if value is None: - return False - elif run_validators and not validator(value): + if value is None or run_validators and not validator(value): return False return True diff --git a/adventofcode/2020/day5/day5.py b/adventofcode/2020/day5/day5.py index 8ed43b2..ddfcf45 100644 --- a/adventofcode/2020/day5/day5.py +++ b/adventofcode/2020/day5/day5.py @@ -1,5 +1,4 @@ #! /usr/bin/env python3 -from itertools import product from bisect import bisect diff --git a/adventofcode/2020/day5/tests.py b/adventofcode/2020/day5/tests.py index 32ace84..68ffe4f 100644 --- a/adventofcode/2020/day5/tests.py +++ b/adventofcode/2020/day5/tests.py @@ -1,6 +1,7 @@ #! /usr/bin/env python3 from day5 import * + def tests(): inputs = { "FBFBBFFRLR": (44, 5, 357), diff --git a/adventofcode/2021/day3/day3.py b/adventofcode/2021/day3/day3.py index e17162a..f1c32ac 100644 --- a/adventofcode/2021/day3/day3.py +++ b/adventofcode/2021/day3/day3.py @@ -58,7 +58,7 @@ def part2(inp): def main(input_file): with open(input_file) as f: - entries = [x.rstrip() for x in f.readlines()] + entries = [x.rstrip() for x in f] part1(entries) part2(entries) diff --git a/adventofcode/2021/day4/day4.py b/adventofcode/2021/day4/day4.py index d657a80..e8a9268 100644 --- a/adventofcode/2021/day4/day4.py +++ b/adventofcode/2021/day4/day4.py @@ -1,5 +1,6 @@ -from dataclasses import dataclass from collections import deque +from dataclasses import dataclass + @dataclass class BingoItem: diff --git a/adventofcode/2021/day5/day5.py b/adventofcode/2021/day5/day5.py index dcc6313..79cf0d3 100644 --- a/adventofcode/2021/day5/day5.py +++ b/adventofcode/2021/day5/day5.py @@ -1,5 +1,6 @@ from collections import defaultdict + def main(infile): points = defaultdict(int) with open(infile) as f: diff --git a/adventofcode/2021/day6/day6.py b/adventofcode/2021/day6/day6.py index c2106f6..f3cb9e6 100644 --- a/adventofcode/2021/day6/day6.py +++ b/adventofcode/2021/day6/day6.py @@ -1,4 +1,5 @@ -from collections import defaultdict, Counter +from collections import Counter, defaultdict + def calculate_fishes(inp, days): fishes = Counter(inp) diff --git a/adventofcode/2021/day7/day7.py b/adventofcode/2021/day7/day7.py index d6a2ee0..e64b80a 100644 --- a/adventofcode/2021/day7/day7.py +++ b/adventofcode/2021/day7/day7.py @@ -1,5 +1,6 @@ from collections import OrderedDict + def part1(crabs): moves = OrderedDict() for pos in range(min(crabs), max(crabs) + 1): diff --git a/adventofcode/2022/day3/day3.py b/adventofcode/2022/day3/day3.py index 72802c1..aca5942 100644 --- a/adventofcode/2022/day3/day3.py +++ b/adventofcode/2022/day3/day3.py @@ -1,5 +1,5 @@ -from itertools import zip_longest from functools import reduce +from itertools import zip_longest from operator import and_ diff --git a/adventofcode/2023/day10/day10.py b/adventofcode/2023/day10/day10.py index acdf5b8..80dafed 100644 --- a/adventofcode/2023/day10/day10.py +++ b/adventofcode/2023/day10/day10.py @@ -1,6 +1,5 @@ -from typing import Dict, List, Set, Tuple -from dataclasses import dataclass from collections import defaultdict +from dataclasses import dataclass from enum import Enum @@ -42,7 +41,7 @@ PIPES = { PIPES_REVERSE_LOOKUP = {v: k for k,v in PIPES.items()} -def find_start_position(grid: List[str]) -> Vec2d: +def find_start_position(grid: list[str]) -> Vec2d: for y, row in enumerate(grid): for x, c in enumerate(row): if c == "S": @@ -50,7 +49,7 @@ def find_start_position(grid: List[str]) -> Vec2d: raise RuntimeError("The start position was not found") -def update_start_symbol(grid: List[str], start_pos: Vec2d): +def update_start_symbol(grid: list[str], start_pos: Vec2d): """ Updates the map by replacing the start symbol "S" with its actual corresponding pipe """ @@ -82,7 +81,7 @@ def update_start_symbol(grid: List[str], start_pos: Vec2d): grid[start_pos.y] = grid[start_pos.y].replace("S", pipe) -def parse_graph(grid: List[str]) -> Dict[Vec2d, List[Vec2d]]: +def parse_graph(grid: list[str]) -> dict[Vec2d, list[Vec2d]]: graph = defaultdict(list) for y, row in enumerate(grid): @@ -95,7 +94,7 @@ def parse_graph(grid: List[str]) -> Dict[Vec2d, List[Vec2d]]: return graph -def traverse_graph(graph, start_pos) -> Tuple[int, Set[Vec2d]]: +def traverse_graph(graph, start_pos) -> tuple[int, set[Vec2d]]: """ traverse the graph using BFS, return the path and the find the length of the longest path in the graph @@ -154,5 +153,5 @@ if __name__ == "__main__": infile = sys.argv[1] with open(infile) as f: - lines = [l.rstrip() for l in f.readlines()] + lines = [l.rstrip() for l in f] main(lines) diff --git a/adventofcode/2023/day3/day3.py b/adventofcode/2023/day3/day3.py index a961c83..2a8681f 100644 --- a/adventofcode/2023/day3/day3.py +++ b/adventofcode/2023/day3/day3.py @@ -1,9 +1,9 @@ -from typing import Tuple, List, Set from dataclasses import dataclass + @dataclass(frozen=True) class Item: - pos: Tuple[int, int] + pos: tuple[int, int] symbol: str @@ -12,8 +12,8 @@ def browse_schema(schema): buf = [] max_row, max_col = len(schema), len(schema[0]) - symbols: List[Tuple[Item, Set[Item]]] = [] - numbers: List[Item] = [] + symbols: list[tuple[Item, set[Item]]] = [] + numbers: list[Item] = [] for y in range(max_row): for x in range(max_col): @@ -61,13 +61,13 @@ def part2(symbols, numbers): -def is_engine_part(neighbors: List[Item]) -> bool: +def is_engine_part(neighbors: list[Item]) -> bool: # get list of symbols (not '.', \n or a number) symbols = filter(lambda x: not x.symbol.isnumeric() and not x.symbol in (".", "\n"), neighbors) return next(symbols, None) is not None -def get_neighbors(pos: Tuple[int, int], length: int, schema: List[List[str]]) -> List[Item]: +def get_neighbors(pos: tuple[int, int], length: int, schema: list[list[str]]) -> list[Item]: x, y = pos start_x = x - length neighbors = [get_neighbors_of((x, y), schema) for x in range(start_x, x)] @@ -75,10 +75,10 @@ def get_neighbors(pos: Tuple[int, int], length: int, schema: List[List[str]]) - return neighbors -def get_neighbors_of(pos: Tuple[int, int], schema: List[List[str]]) -> List[Item]: +def get_neighbors_of(pos: tuple[int, int], schema: list[list[str]]) -> list[Item]: max_row, max_col = len(schema), len(schema[0]) x, y = pos - neighbors: List[Item] = [] + neighbors: list[Item] = [] # top if y-1 >= 0: @@ -112,5 +112,5 @@ if __name__ == "__main__": import sys infile = sys.argv[1] with open(infile) as f: - schema = [[c for c in line] for line in f.readlines()] + schema = [[c for c in line] for line in f] browse_schema(schema) diff --git a/adventofcode/2023/day5/day5.py b/adventofcode/2023/day5/day5.py index 72cb8f3..1b0c776 100644 --- a/adventofcode/2023/day5/day5.py +++ b/adventofcode/2023/day5/day5.py @@ -27,8 +27,7 @@ def part2(sections): print(f"calculate_for_subseeds(subseeds len={len(subseeds)})") res = calculate_for_subseeds(subseeds, sections) mini = min(res) - if mini < min_seed: - min_seed = mini + min_seed = min(min_seed, mini) print(f"Part 2 {min_seed}") @@ -58,8 +57,8 @@ def parse_input(infile): if __name__ == "__main__": - import sys import os + import sys SCRIPTPATH = os.path.dirname(os.path.realpath(__file__)) infile = next(iter(sys.argv[1:]), None) diff --git a/adventofcode/2023/day6/day6.py b/adventofcode/2023/day6/day6.py index ff2ded6..16ae674 100644 --- a/adventofcode/2023/day6/day6.py +++ b/adventofcode/2023/day6/day6.py @@ -10,7 +10,7 @@ def calculate_wins(data): total = 1 for time, record in data: ways = 0 - for n in range(0, time+1): + for n in range(time+1): speed = n distance = (time-n) * speed if distance > record: diff --git a/adventofcode/2023/day8/day8.py b/adventofcode/2023/day8/day8.py index 8c19236..abd2b3e 100644 --- a/adventofcode/2023/day8/day8.py +++ b/adventofcode/2023/day8/day8.py @@ -1,7 +1,8 @@ -import re import math +import re from itertools import cycle + def parse_input(infile): with open(infile) as f: content = f.read().rstrip() @@ -63,8 +64,8 @@ def part2(directions, nodes): if __name__ == "__main__": - import sys import os + import sys SCRIPTPATH = os.path.dirname(os.path.realpath(__file__)) infile = sys.argv[1] if len(sys.argv) == 2 else "example.txt" diff --git a/adventofcode/2023/day9/day9.py b/adventofcode/2023/day9/day9.py index 7d91ab1..ff86f5c 100644 --- a/adventofcode/2023/day9/day9.py +++ b/adventofcode/2023/day9/day9.py @@ -1,6 +1,6 @@ def parse_input(infile): with open(infile) as f: - return [[int(x) for x in l.strip().split()] for l in f.readlines()] + return [[int(x) for x in l.strip().split()] for l in f] def process_line(line): @@ -25,8 +25,8 @@ def solve(data): if __name__ == "__main__": - import sys import os + import sys SCRIPTPATH = os.path.dirname(os.path.realpath(__file__)) infile = sys.argv[1] if len(sys.argv) == 2 else "example.txt" data = parse_input(os.path.join(SCRIPTPATH, infile)) diff --git a/adventofcode/2024/day1/day1.py b/adventofcode/2024/day1/day1.py index 6f5bc01..b95e633 100644 --- a/adventofcode/2024/day1/day1.py +++ b/adventofcode/2024/day1/day1.py @@ -2,7 +2,7 @@ from collections import Counter def main(lines): - firsts, seconds = list(sorted(x[0] for x in lines)), list(sorted(x[1] for x in lines)) + firsts, seconds = sorted(x[0] for x in lines), sorted(x[1] for x in lines) total = sum(abs(a - b) for (a, b) in zip(firsts, seconds)) print("Part 1: ", total) diff --git a/adventofcode/2024/day10/day10.py b/adventofcode/2024/day10/day10.py index b0cb369..42e7de8 100644 --- a/adventofcode/2024/day10/day10.py +++ b/adventofcode/2024/day10/day10.py @@ -63,6 +63,6 @@ if __name__ == "__main__": import sys infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" with open(infile) as f: - grid = [list(map(int, list(l.rstrip()))) for l in f.readlines()] + grid = [list(map(int, list(l.rstrip()))) for l in f] main(grid) diff --git a/adventofcode/2024/day11/day11.py b/adventofcode/2024/day11/day11.py index 5d89fca..7ade174 100644 --- a/adventofcode/2024/day11/day11.py +++ b/adventofcode/2024/day11/day11.py @@ -1,5 +1,6 @@ from collections import Counter + def main(data): part1 = run(data, 25) print("Part 1: ", part1) diff --git a/adventofcode/2024/day12/day12.py b/adventofcode/2024/day12/day12.py index 451f182..957bef1 100644 --- a/adventofcode/2024/day12/day12.py +++ b/adventofcode/2024/day12/day12.py @@ -1,5 +1,4 @@ from dataclasses import dataclass -from collections import defaultdict @dataclass(frozen=True) @@ -78,6 +77,6 @@ if __name__ == "__main__": import sys infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" with open(infile) as f: - grid = [l.rstrip() for l in f.readlines()] + grid = [l.rstrip() for l in f] main(grid) diff --git a/adventofcode/2024/day14/day14.py b/adventofcode/2024/day14/day14.py index 7cdc7f1..4e0f722 100644 --- a/adventofcode/2024/day14/day14.py +++ b/adventofcode/2024/day14/day14.py @@ -1,5 +1,5 @@ -from math import prod from collections import Counter +from math import prod def parse_bots(lines): diff --git a/adventofcode/2024/day15/day15.py b/adventofcode/2024/day15/day15.py index 2c1ab0e..20b87ff 100644 --- a/adventofcode/2024/day15/day15.py +++ b/adventofcode/2024/day15/day15.py @@ -9,7 +9,7 @@ DIRECTIONS = { def find_start_pos(grid): for y, row in enumerate(grid): for x, _ in enumerate(row): - if grid[y][x] == "@": + if row[x] == "@": return complex(x, y) @@ -69,7 +69,7 @@ def calculate_gps_coords(grid): total = 0 for y, row in enumerate(grid): for x, _ in enumerate(row): - if grid[y][x] == "O": + if row[x] == "O": total += 100*y + x return total diff --git a/adventofcode/2024/day16/day16.py b/adventofcode/2024/day16/day16.py index bf4a781..cbba604 100644 --- a/adventofcode/2024/day16/day16.py +++ b/adventofcode/2024/day16/day16.py @@ -1,7 +1,6 @@ from dataclasses import dataclass from heapq import heappop, heappush - DIRECTIONS = { ">": 1 + 0j, # EAST "v": 0 + 1j, # SOUTH @@ -27,9 +26,9 @@ def find_start_and_goal(grid): start, goal = None, None for y, row in enumerate(grid): for x, _ in enumerate(row): - if grid[y][x] == "S": + if row[x] == "S": start = complex(x, y) - elif grid[y][x] == "E": + elif row[x] == "E": goal = complex(x, y) return start, goal @@ -112,6 +111,6 @@ if __name__ == "__main__": import sys infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" with open(infile) as f: - grid = [list(l.rstrip()) for l in f.readlines()] + grid = [list(l.rstrip()) for l in f] main(grid) diff --git a/adventofcode/2024/day18/day18.py b/adventofcode/2024/day18/day18.py index 82ddb15..04dbc5a 100644 --- a/adventofcode/2024/day18/day18.py +++ b/adventofcode/2024/day18/day18.py @@ -1,6 +1,5 @@ from dataclasses import dataclass -from heapq import heappush, heappop - +from heapq import heappop, heappush DIRECTIONS = ( 1 + 0j, # EAST diff --git a/adventofcode/2024/day4/day4.py b/adventofcode/2024/day4/day4.py index b8ddc36..e76f3c0 100644 --- a/adventofcode/2024/day4/day4.py +++ b/adventofcode/2024/day4/day4.py @@ -47,16 +47,16 @@ def part2(grid): if grid[y+1][x+1] != "A": # center letter is always "A" continue # M.S / .A. / M.S - if grid[y][x] == "M" and grid[y][x+2] == "S" and grid[y+2][x] == "M" and grid[y+2][x+2] == "S": + if row[x] == "M" and row[x+2] == "S" and grid[y+2][x] == "M" and grid[y+2][x+2] == "S": count += 1 # M.M / .A. / S.S - if grid[y][x] == "M" and grid[y][x+2] == "M" and grid[y+2][x] == "S" and grid[y+2][x+2] == "S": + if row[x] == "M" and row[x+2] == "M" and grid[y+2][x] == "S" and grid[y+2][x+2] == "S": count += 1 # S.M / .A. / S.M - if grid[y][x] == "S" and grid[y][x+2] == "M" and grid[y+2][x] == "S" and grid[y+2][x+2] == "M": + if row[x] == "S" and row[x+2] == "M" and grid[y+2][x] == "S" and grid[y+2][x+2] == "M": count += 1 # S.S / .A. / M.M - if grid[y][x] == "S" and grid[y][x+2] == "S" and grid[y+2][x] == "M" and grid[y+2][x+2] == "M": + if row[x] == "S" and row[x+2] == "S" and grid[y+2][x] == "M" and grid[y+2][x+2] == "M": count += 1 print("Part 2: ", count) @@ -66,7 +66,7 @@ if __name__ == "__main__": import sys infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" with open(infile) as f: - grid = [l.rstrip() for l in f.readlines()] + grid = [l.rstrip() for l in f] part1(grid) part2(grid) diff --git a/adventofcode/2024/day5/day5.py b/adventofcode/2024/day5/day5.py index c20a42e..b333da6 100644 --- a/adventofcode/2024/day5/day5.py +++ b/adventofcode/2024/day5/day5.py @@ -1,4 +1,3 @@ -from collections import defaultdict from itertools import pairwise diff --git a/adventofcode/2024/day6/day6.py b/adventofcode/2024/day6/day6.py index 90a667d..f0fb435 100644 --- a/adventofcode/2024/day6/day6.py +++ b/adventofcode/2024/day6/day6.py @@ -1,6 +1,5 @@ -from itertools import cycle from dataclasses import dataclass -from pprint import pprint +from itertools import cycle @dataclass(frozen=True) @@ -75,6 +74,6 @@ if __name__ == "__main__": import sys infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" with open(infile) as f: - grid = [list(l.rstrip()) for l in f.readlines()] + grid = [list(l.rstrip()) for l in f] main(grid) diff --git a/adventofcode/2024/day7/day7.py b/adventofcode/2024/day7/day7.py index 4fc8b3e..9c7b68e 100644 --- a/adventofcode/2024/day7/day7.py +++ b/adventofcode/2024/day7/day7.py @@ -30,7 +30,7 @@ if __name__ == "__main__": import sys infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" with open(infile) as f: - data = [l.rstrip().split(": ") for l in f.readlines()] + data = [l.rstrip().split(": ") for l in f] data = [(int(a), tuple(map(int, b.split(" ")))) for a, b in data] main(data) diff --git a/adventofcode/2025/day9/day9.py b/adventofcode/2025/day9/day9.py index fffed39..2f3912f 100644 --- a/adventofcode/2025/day9/day9.py +++ b/adventofcode/2025/day9/day9.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 import fileinput -from sys import argv def area(a, b): @@ -38,8 +37,7 @@ def generate_ppm(inp, scale=100): with open("test.ppm", "w") as f: f.write(f"P3\n{width} {height}\n255\n") for row in arr: - for cell in row: - f.write(f"{cell * 255} 0 0 ") + f.writelines(f"{cell * 255} 0 0 " for cell in row) f.write("\n") print("PPM file written to test.ppm") diff --git a/adventofcode/helper.py b/adventofcode/helper.py index 41f4f68..c89fbb5 100644 --- a/adventofcode/helper.py +++ b/adventofcode/helper.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 import os import re import subprocess @@ -10,8 +9,7 @@ from pathlib import Path MIN_YEAR = 2015 MAX_YEAR = 2025 ROOTPATH = Path(os.path.dirname(os.path.realpath(__file__))) -TEMPLATE = """#!/usr/bin/env python3 -import fileinput +TEMPLATE = """import fileinput def main(inp): diff --git a/adventofcode/intcode/__init__.py b/adventofcode/intcode/__init__.py index ec644a1..40bfc8e 100644 --- a/adventofcode/intcode/__init__.py +++ b/adventofcode/intcode/__init__.py @@ -1 +1 @@ -from .intcode import interpret_intcode, Interpreter, Operation, Mode +from .intcode import Interpreter, Mode, Operation, interpret_intcode diff --git a/adventofcode/intcode/intcode.py b/adventofcode/intcode/intcode.py index edaf987..a49fe73 100644 --- a/adventofcode/intcode/intcode.py +++ b/adventofcode/intcode/intcode.py @@ -1,8 +1,7 @@ #! /usr/bin/env python3 -from collections import defaultdict -from enum import Enum import logging import os +from enum import Enum loglevel = (os.getenv("LOGLEVEL") or "WARN").upper() logging.basicConfig(format="%(levelname)s:%(message)s", level=loglevel) @@ -38,7 +37,7 @@ class Instruction: self.memory = memory self.opcode = memory[ip] # A B C D E - # 0 1 1 0 3 + # 0 1 1 0 3 # A B C modes, DE opcode self.operation = Operation(self.opcode % 100) self.modes = [Mode(get_nth_digit(n, self.opcode)) for n in range(2, 5)] @@ -140,13 +139,13 @@ class Instruction: match self.modes[offset - 1]: case Mode.POSITION: return value case Mode.RELATIVE: return value + self.base - case _: raise ValueError(f"{self.modes[i]}") + case _: raise ValueError(f"{self.modes[offset - 1]}") def _get_parameters(self): first = self._get_value(1) second = self._get_value(2) return first, second - + def _write(self, address, value): while address >= len(self.memory): self.memory += [0] * len(self.memory) @@ -191,4 +190,3 @@ def interpret_intcode(program, stdin=[]): interpreter = Interpreter(program, stdin) interpreter.interpret(break_on_output=False) return interpreter - diff --git a/adventofcode/intcode/tests.py b/adventofcode/intcode/tests.py index f3a6a8c..1966ea9 100644 --- a/adventofcode/intcode/tests.py +++ b/adventofcode/intcode/tests.py @@ -1,5 +1,4 @@ # Run with pytest -import logging from intcode import * @@ -82,18 +81,13 @@ def test_day9_base(): assert interpreter.base == 2025 -def test_day9_relative(): - program = [109,6,21001,9,25,1,104,0,99,49] - ret = interpret_intcode(program) - assert ret.stdout == [74] - - def test_day9_quine(): quine = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99] run_test(quine, expected_out=quine) def test_day9_relative(): + run_test([109,6,21001,9,25,1,104,0,99,49], expected_out=[74]) run_test([109, -1, 4, 1, 99], expected_out=[-1]) run_test([109, -1, 104, 1, 99], expected_out=[1]) run_test([109, -1, 204, 1, 99], expected_out=[109]) @@ -107,5 +101,5 @@ def test_day9_relative(): def test_fac(): # factorial test fac = [3,29,1007,29,2,28,1005,28,24,2,27,29,27,1001,29,-1,29,1101,0,0,28,1006,28,2,4,27,99,1,0,0] - res = interpret_intcode(fac, [4]) + res = interpret_intcode(fac, [4]) assert res.stdout == [24] diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..adf0de9 --- /dev/null +++ b/uv.lock @@ -0,0 +1,8 @@ +version = 1 +revision = 3 +requires-python = ">=3.11" + +[[package]] +name = "adventofcode" +version = "1.0.0" +source = { editable = "." }