make 2020 compatible with run.py

This commit is contained in:
2025-07-30 01:00:27 +02:00
parent f9abb90915
commit 9c76828788
14 changed files with 119 additions and 81 deletions

View File

@@ -17,5 +17,8 @@ def part2(inp):
if __name__ == "__main__": if __name__ == "__main__":
with open("input.txt") as f: import fileinput
part2(f.readlines()) lines = [x for x in fileinput.input()]
part1(lines)
part2(lines)

View File

@@ -18,7 +18,13 @@ def part2(adapters):
return max(counts.values()) return max(counts.values())
if __name__ == "__main__": def main(f):
adapters = sorted(int(l.rstrip()) for l in open("input.txt")) adapters = sorted(int(l.rstrip()) for l in f)
print(part1(adapters)) print(part1(adapters))
print(part2(adapters)) print(part2(adapters))
if __name__ == "__main__":
import fileinput
main(fileinput.input())

View File

@@ -27,7 +27,8 @@ def step(grid, rules):
if __name__ == "__main__": if __name__ == "__main__":
with open("input.txt") as infile: import sys
with open(sys.argv[1]) as infile:
grid = list("".join(infile.read().splitlines())) grid = list("".join(infile.read().splitlines()))
print("Part 1 ", main(grid, rules=part1_rules)) print("Part 1 ", main(grid, rules=part1_rules))
print("Part 2 ", main(grid, rules=part2_rules)) print("Part 2 ", main(grid, rules=part2_rules))

14
2020/day2/day2.py Normal file
View File

@@ -0,0 +1,14 @@
import part1
import part2
def main(lines):
part1.main(lines)
part2.main(lines)
if __name__ == "__main__":
import fileinput
lines = [x for x in fileinput.input()]
main(lines)

View File

@@ -15,14 +15,10 @@ def test_password(line):
return count in repeat_range return count in repeat_range
def main(inp): def main(passwds):
with open(inp) as passwds: valid_counter = 0
valid_counter = 0 for l in passwds:
for l in passwds: if test_password(l):
if test_password(l): valid_counter += 1
valid_counter += 1 print(f"Number of valid password in input : {valid_counter}")
print(f"Number of valid password in input : {valid_counter}")
if __name__ == "__main__":
main('./input.txt')

View File

@@ -19,14 +19,10 @@ def test_password(line):
pwd[second_pos - 1] == letter) pwd[second_pos - 1] == letter)
def main(inp): def main(passwds):
with open(inp) as passwds: valid_counter = 0
valid_counter = 0 for l in passwds:
for l in passwds: if test_password(l):
if test_password(l): valid_counter += 1
valid_counter += 1 print(f"Number of valid password in input : {valid_counter}")
print(f"Number of valid password in input : {valid_counter}")
if __name__ == "__main__":
main('./input.txt')

View File

@@ -15,14 +15,12 @@ def check_slope_for_trees(plan, x_right=3, y_down=1):
return tree_count return tree_count
def part1(inp): def part1(plan):
plan = [line.rstrip() for line in open(inp)]
tree_count = check_slope_for_trees(plan) tree_count = check_slope_for_trees(plan)
print(f"number of trees : {tree_count}") print(f"number of trees : {tree_count}")
def part2(inp): def part2(plan):
plan = [line.rstrip() for line in open(inp)]
slopes = [{"x": 1, "y": 1}, {"x": 3, "y": 1}, {"x": 5, "y": 1}, {"x": 7, "y": 1}, {"x": 1, "y": 2}] slopes = [{"x": 1, "y": 1}, {"x": 3, "y": 1}, {"x": 5, "y": 1}, {"x": 7, "y": 1}, {"x": 1, "y": 2}]
tree_product = 1 tree_product = 1
for slope in slopes: for slope in slopes:
@@ -31,6 +29,14 @@ def part2(inp):
print(f"slope {slope} number of trees : {tree_count}") print(f"slope {slope} number of trees : {tree_count}")
print(f"Cumulative product of tress : {tree_product}") print(f"Cumulative product of tress : {tree_product}")
def main(f):
lines = [line.rstrip() for line in f]
part1(lines)
part2(lines)
if __name__ == "__main__": if __name__ == "__main__":
part1('input.txt') import fileinput
part2('input.txt') main(fileinput.input())

View File

@@ -3,17 +3,20 @@ import re
def main(inp): def main(inp):
inp = open(inp).read().split('\n\n') inp = open(inp).read().rstrip().split('\n\n')
valid_passeports = 0 valid_passeports_1, valid_passeports_2 = 0, 0
for l in inp: for l in inp:
l = re.split('[\n\s]', l) l = re.split(r'[\n\s]', l)
passeport = dict(p.split(':') for p in l) passeport = dict(p.split(':') for p in l)
if check_passeport(passeport): if check_passeport(passeport):
valid_passeports += 1 valid_passeports_1 += 1
print("Valid passeports ", valid_passeports) if check_passeport(passeport, run_validators=True):
valid_passeports_2 += 1
print("Part 1: valid passeports: ", valid_passeports_1)
print("Part 2: valid passeports: ", valid_passeports_2)
def check_passeport(passeport): def check_passeport(passeport, run_validators=False):
fields = [ fields = [
('byr', lambda v: 1920 <= int(v) <= 2002), # (Birth Year) ('byr', lambda v: 1920 <= int(v) <= 2002), # (Birth Year)
('iyr', lambda v: 2010 <= int(v) <= 2020), # (Issue Year) ('iyr', lambda v: 2010 <= int(v) <= 2020), # (Issue Year)
@@ -28,7 +31,7 @@ def check_passeport(passeport):
value = passeport.get(field) value = passeport.get(field)
if value is None: if value is None:
return False return False
elif not validator(value): elif run_validators and not validator(value):
return False return False
return True return True
@@ -44,4 +47,6 @@ def validate_height(v):
if __name__ == "__main__": if __name__ == "__main__":
main('input.txt') import sys
main(sys.argv[1])

View File

@@ -3,20 +3,18 @@ from itertools import product
from bisect import bisect from bisect import bisect
def main(filename): def main(inp):
results = {} results = {}
with open(filename) as inp: for line in inp:
for line in inp: boarding_pass = line.rstrip()
boarding_pass = line.rstrip() row, col = parse_boarding_pass(boarding_pass)
row, col = parse_boarding_pass(boarding_pass) seat_id = get_seat_id(row, col)
seat_id = get_seat_id(row, col) results[boarding_pass] = (row, col, seat_id)
results[boarding_pass] = (row, col, seat_id)
part1(results) part1(results)
part2(results) part2(results)
def part1(results): def part1(results):
# part 1
max_seat_id = max(x[2] for x in results.values()) max_seat_id = max(x[2] for x in results.values())
print("Max seat ID: ", max_seat_id) print("Max seat ID: ", max_seat_id)
@@ -66,4 +64,5 @@ def get_seat_id(row, col):
if __name__ == "__main__": if __name__ == "__main__":
main('input.txt') import fileinput
main(fileinput.input())

View File

@@ -2,8 +2,7 @@
from collections import Counter from collections import Counter
def part1(inp): def part1(groups):
groups = open(inp).read().split("\n\n")
number_of_questions = 0 number_of_questions = 0
for group in groups: for group in groups:
unique_questions = set(group.replace("\n", "")) unique_questions = set(group.replace("\n", ""))
@@ -11,11 +10,9 @@ def part1(inp):
print(number_of_questions) print(number_of_questions)
def part2(inp): def part2(groups):
# number of questions for which everyone in a group answered 'yes' # number of questions for which everyone in a group answered 'yes'
number_of_questions = 0 number_of_questions = 0
groups = open(inp).read().split("\n\n")
for group in groups: for group in groups:
group_length = group.count("\n") + 1 group_length = group.count("\n") + 1
group_counter = Counter(group.replace("\n", "")) group_counter = Counter(group.replace("\n", ""))
@@ -25,5 +22,9 @@ def part2(inp):
if __name__ == "__main__": if __name__ == "__main__":
part1("input.txt") import sys
part2("input.txt") inp = sys.argv[1]
groups = open(inp).read().split("\n\n")
part1(groups)
part2(groups)

View File

@@ -3,19 +3,18 @@ import re
from collections import defaultdict, deque from collections import defaultdict, deque
def main(inp): def main(input_rules):
with open(inp) as input_rules: rules = parse_rules(input_rules)
rules = parse_rules(input_rules) reverse_rules = build_reverse_rules(rules)
reverse_rules = build_reverse_rules(rules) print(part1(reverse_rules))
print(part1(reverse_rules)) print(part2(rules, "shiny gold"))
print(part2(rules, "shiny gold"))
def parse_rules(input_rules): def parse_rules(input_rules):
rules = {} rules = {}
for input_rule in input_rules: for input_rule in input_rules:
color, rule = input_rule.split(" bags contain ") color, rule = input_rule.split(" bags contain ")
rules[color] = {color: int(number) for number, color in re.findall('(\d+) (\w+ \w+)', rule)} rules[color] = {color: int(number) for number, color in re.findall(r'(\d+) (\w+ \w+)', rule)}
return rules return rules
@@ -44,4 +43,5 @@ def part2(rules, color):
if __name__ == "__main__": if __name__ == "__main__":
main("input.txt") import fileinput
main(fileinput.input())

View File

@@ -43,7 +43,13 @@ def generate_permutation(instructions, line, index):
return permutation return permutation
if __name__ == "__main__": def main(inp):
instructions = [line.rstrip() for line in open("input.txt")] instructions = [line.rstrip() for line in fileinput.input()]
print("Part 1 : (ip, acc) ", part1(instructions)[1]) print("Part 1 : (ip, acc) ", part1(instructions)[1])
print("Part 2 : (ip, acc) ", part2(instructions)) print("Part 2 : (ip, acc) ", part2(instructions))
if __name__ == "__main__":
import fileinput
main(fileinput.input())

View File

@@ -2,14 +2,12 @@
import itertools import itertools
def part1(inp): def part1(lines):
preamble_size = 25 preamble_size = 25
with open(inp) as infile: for nums in window(lines, preamble_size + 1):
cleanfile = (int(l.rstrip()) for l in infile) candidate = nums[-1]
for nums in window(cleanfile, preamble_size + 1): if not test_number(candidate, nums[:-1]):
candidate = nums[-1] return candidate
if not test_number(candidate, nums[:-1]):
return candidate
return -1 return -1
@@ -28,8 +26,7 @@ def test_number(num, previous):
return num in sums return num in sums
def part2(infile, target: int): def part2(lines, target: int):
lines = [int(l.rstrip()) for l in open(infile).readlines()]
total = 0 total = 0
visited = [] visited = []
for index, _ in enumerate(lines): for index, _ in enumerate(lines):
@@ -44,7 +41,14 @@ def part2(infile, target: int):
total = 0 total = 0
if __name__ == "__main__": def main(f):
invalid_number = part1("input.txt") lines = [int(l.rstrip()) for l in f]
invalid_number = part1(lines)
print("part1 ", invalid_number) print("part1 ", invalid_number)
print("part2 ", part2("input.txt", invalid_number)) print("part2 ", part2(lines, invalid_number))
if __name__ == "__main__":
import fileinput
main(fileinput.input())

9
run.py
View File

@@ -50,7 +50,7 @@ def main(year, day):
input_path = path / Path("input.txt") input_path = path / Path("input.txt")
if script_path.exists(): if script_path.exists():
if not input_path.exists(): if not input_path.exists():
print(f"Downloading input file {input_path}") print(f"- downloading input file {input_path}")
get_auth() get_auth()
with open(input_path, "wb") as f: with open(input_path, "wb") as f:
res = get_input_file(year, day) res = get_input_file(year, day)
@@ -60,13 +60,14 @@ def main(year, day):
def run_day(script_path, input_path): def run_day(script_path, input_path):
try: try:
print(f"> running {script_path}")
start = time.time() start = time.time()
res = subprocess.run([sys.executable, script_path.absolute(), input_path.absolute()], check=True, stdout=subprocess.PIPE, timeout=30) res = subprocess.run([sys.executable, script_path.absolute(), input_path.absolute()], check=True, stdout=subprocess.PIPE, timeout=30)
elapsed = time.time() - start elapsed = time.time() - start
#print(res.stdout) print(res.stdout.decode())
print(f"ran {script_path} in {elapsed:.3f}s") print(f"> ran {script_path} in {elapsed:.3f}s")
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
print(f"timeout {script_path} after 30s", file=sys.stderr) print(f"> timeout {script_path} after 30s", file=sys.stderr)
if __name__ == "__main__": if __name__ == "__main__":