adventofcode 25.7__py3-none-any.whl → 25.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
adventofcode/__about__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "25.7"
1
+ __version__ = "25.9"
adventofcode/__init__.py CHANGED
@@ -6,6 +6,7 @@ import time
6
6
  from collections.abc import Callable
7
7
  from contextlib import contextmanager
8
8
  from pathlib import Path
9
+ from timeit import Timer
9
10
  from typing import Any
10
11
 
11
12
  import percache
@@ -129,6 +130,18 @@ class AoC:
129
130
  perf.value = answer
130
131
  submit(year=self.year, day=self.day, level=2, answer=answer)
131
132
 
133
+ def submit_p1_benchmark(self):
134
+ inp = self.get_input()
135
+ num_loops, total_time = Timer(lambda: self.part_1(inp)).autorange()
136
+ console.log(f"{format_time(total_time / num_loops)} to {PART_1_RETURN_STR}")
137
+ submit(year=self.year, day=self.day, level=1, answer=self.part_1(inp))
138
+
139
+ def submit_p2_benchmark(self):
140
+ inp = self.get_input()
141
+ num_loops, total_time = Timer(lambda: self.part_2(inp)).autorange()
142
+ console.log(f"{format_time(total_time / num_loops)} to {PART_2_RETURN_STR}")
143
+ submit(year=self.year, day=self.day, level=2, answer=self.part_2(inp))
144
+
132
145
 
133
146
  @cache
134
147
  def get_puzzle(day: int, year: int, part: int) -> str:
adventofcode/cli.py CHANGED
@@ -66,7 +66,7 @@ def init_templates(year: int, output_dir: Path, num_days: int) -> None:
66
66
  console.log(f"Skipping {filename} (already exists)")
67
67
  continue
68
68
 
69
- filepath.write_text(TEMPLATE.format(day=day, year=year))
69
+ filepath.write_text(TEMPLATE.format(day=day, year=year), encoding="utf-8")
70
70
  console.log(f"Created {filename}")
71
71
 
72
72
  gitignore_path = output_dir / ".gitignore"
@@ -92,7 +92,8 @@ def init_templates(year: int, output_dir: Path, num_days: int) -> None:
92
92
  "# You can find it in your browser's developer tools after logging in to adventofcode.com. \n"
93
93
  "# The name of the cookie is `session`.\n"
94
94
  'AOC_SESSION=""\n'
95
- f"AOC_YEAR={year}\n"
95
+ f"AOC_YEAR={year}\n",
96
+ encoding="utf-8",
96
97
  )
97
98
  console.log("Created .env file (remember to set your AOC_SESSION)")
98
99
 
@@ -148,14 +149,15 @@ def time_to_color(seconds: float) -> Color:
148
149
 
149
150
 
150
151
  def run_day(filepath: Path) -> DayResult:
151
- day_num = int(re.sub(r"[^0-9]", "", filepath.stem))
152
+ match = re.match(r"(\d\d)", filepath.stem)
153
+ day_num = int(match.group(1)) if match else 0
152
154
  if datetime.date(AOC_YEAR, 12, day_num) > today_est:
153
155
  return DayResult(day=filepath.stem, status="🕑")
154
156
 
155
157
  result = DayResult(day=filepath.stem)
156
158
 
157
159
  if "adventofcode run" in filepath.read_text():
158
- command = ["adventofcode", "run", str(filepath)]
160
+ command = ["adventofcode", "run", str(filepath), "--benchmark"]
159
161
  else:
160
162
  command = [sys.executable, str(filepath)]
161
163
  try:
@@ -230,30 +232,120 @@ def build_markdown_table(results: list[DayResult], total_time: float, total_part
230
232
  return "\n".join(lines)
231
233
 
232
234
 
233
- def update_readme(readme_path: Path, results_table: str) -> None:
235
+ def get_result_row(table: str, pattern: str) -> str | None:
236
+ table_match = re.search(pattern, table, flags=re.MULTILINE)
237
+ return None if table_match is None else table_match.group(0)
238
+
239
+
240
+ def get_time_diff(old_day_row: str, new_day_row: str) -> list[float]:
241
+ pattern = r"(\d+\.\d+)(ms|s)"
242
+
243
+ def parse_time(match: tuple[str, str]) -> float:
244
+ val = float(match[0])
245
+ return val * 1000 if match[1] == "s" else val
246
+
247
+ matches_old = re.findall(pattern, old_day_row)
248
+ matches_new = re.findall(pattern, new_day_row)
249
+
250
+ if len(matches_old) >= 2 and len(matches_new) >= 2:
251
+ part_1_time_old = parse_time(matches_old[0])
252
+ part_2_time_old = parse_time(matches_old[1])
253
+
254
+ part_1_time_new = parse_time(matches_new[0])
255
+ part_2_time_new = parse_time(matches_new[1])
256
+ return [part_1_time_new - part_1_time_old, part_2_time_new - part_2_time_old]
257
+ if len(matches_new) >= 2:
258
+ return [parse_time(matches_new[0]), parse_time(matches_new[1])]
259
+ return [0.0, 0.0]
260
+
261
+
262
+ def update_readme(readme_path: Path, results_table: str, path: Path) -> None:
234
263
  """Update the README.md with benchmark results."""
235
264
  marker_start = "<!-- BENCHMARK_RESULTS_START -->"
236
265
  marker_end = "<!-- BENCHMARK_RESULTS_END -->"
237
-
238
266
  if not readme_path.exists():
239
267
  # Create a new README with results
240
- content = f"# Advent of Code\n\n## Benchmark Results\n\n{marker_start}\n{results_table}\n{marker_end}\n"
241
- readme_path.write_text(content)
268
+ content = dedent("""\
269
+ # Advent of Code {AOC_YEAR} 🎄
270
+
271
+ ## Solution Benchmarks
272
+
273
+ {marker_start}
274
+ {results_table}
275
+ {marker_end}
276
+ """).format(
277
+ AOC_YEAR=AOC_YEAR,
278
+ marker_start=marker_start,
279
+ marker_end=marker_end,
280
+ results_table=results_table,
281
+ )
282
+ readme_path.write_text(content, encoding="utf-8")
242
283
  console.log(f"Created {readme_path} with benchmark results")
243
284
  return
244
285
 
245
286
  content = readme_path.read_text()
246
-
247
287
  if marker_start in content and marker_end in content:
248
- # Replace existing results
249
- pattern = re.compile(re.escape(marker_start) + r".*?" + re.escape(marker_end), re.DOTALL)
250
- new_section = f"{marker_start}\n{results_table}\n{marker_end}"
251
- content = pattern.sub(new_section, content)
288
+ if path.is_dir():
289
+ # Replace entire existing results table
290
+ pattern = re.compile(re.escape(marker_start) + r".*?" + re.escape(marker_end), re.DOTALL)
291
+ new_section = f"{marker_start}\n{results_table}\n{marker_end}"
292
+ content = pattern.sub(new_section, content)
293
+ else:
294
+ # strip .py from path
295
+ stem = path.stem
296
+
297
+ # substitute the old day row with the new day row
298
+ day_row_pattern = rf"^(\|\s*{stem}\s*\|).*?(\n)"
299
+ old_day_row = get_result_row(content, day_row_pattern)
300
+ if old_day_row is None:
301
+ console.log(f"[red]Could not extract existing row for path {stem} in README[/red]")
302
+ return
303
+ new_day_row = get_result_row(results_table, day_row_pattern)
304
+ if new_day_row is None:
305
+ console.log(f"[red]Could not find new row for path {stem} in results table[/red]")
306
+ return
307
+ content = re.sub(day_row_pattern, new_day_row, content, flags=re.MULTILINE)
308
+
309
+ # substitute the total day row with new time
310
+ totals_pattern = r"^(\|\s*\*\*Total\*\*\s*\|).*?(\n)"
311
+ old_totals = re.search(totals_pattern, content, flags=re.MULTILINE)
312
+
313
+ time_pattern = r"(\d+\.\d+)(ms|s)"
314
+ matches = re.findall(time_pattern, old_totals.group(0)) if old_totals else []
315
+
316
+ if len(matches) < 3:
317
+ console.log("[red]Could not extract existing totals in README[/red]")
318
+ return
319
+
320
+ def parse_to_ms(val_str: str, unit_str: str) -> float:
321
+ val = float(val_str)
322
+ return val * 1000 if unit_str == "s" else val
323
+
324
+ current_p1_ms = parse_to_ms(matches[0][0], matches[0][1])
325
+ current_p2_ms = parse_to_ms(matches[1][0], matches[1][1])
326
+ current_total_ms = parse_to_ms(matches[2][0], matches[2][1])
327
+
328
+ [part_1_diff_ms, part_2_diff_ms] = get_time_diff(old_day_row, new_day_row)
329
+
330
+ new_p1_ms = current_p1_ms + part_1_diff_ms
331
+ new_p2_ms = current_p2_ms + part_2_diff_ms
332
+ new_total_ms = current_total_ms + part_1_diff_ms + part_2_diff_ms
333
+
334
+ p1_seconds = new_p1_ms / 1000.0
335
+ p2_seconds = new_p2_ms / 1000.0
336
+ total_seconds = new_total_ms / 1000.0
337
+
338
+ p1_str = markdown_color(format_time(p1_seconds), time_to_color(p1_seconds))
339
+ p2_str = markdown_color(format_time(p2_seconds), time_to_color(p2_seconds))
340
+ total_str = markdown_color(format_time(total_seconds), time_to_color(total_seconds))
341
+
342
+ new_totals = f"| **Total** | | {p1_str} | {p2_str} | {total_str} |\n"
343
+ content = re.sub(totals_pattern, new_totals, content, flags=re.MULTILINE)
252
344
  else:
253
345
  # Append results section
254
346
  content += f"\n## Benchmark Results\n\n{marker_start}\n{results_table}\n{marker_end}\n"
255
347
 
256
- readme_path.write_text(content)
348
+ readme_path.write_text(content, encoding="utf-8")
257
349
  console.log(f"Updated {readme_path} with benchmark results")
258
350
 
259
351
 
@@ -275,7 +367,7 @@ def markdown_color(formatted_time: str, color: Color) -> str:
275
367
  def build_console_table(
276
368
  results: list[DayResult], current_running: str | None, total_part_1: float, total_part_2: float, total_time: float
277
369
  ) -> Table:
278
- table = Table(title="Advent of Code Benchmarks")
370
+ table = Table(title=f"Advent of Code {AOC_YEAR} Benchmark")
279
371
  table.add_column("Day", style="cyan", justify="right")
280
372
  table.add_column("Status", justify="center")
281
373
  table.add_column("Part 1", justify="right")
@@ -302,11 +394,12 @@ def build_console_table(
302
394
  return table
303
395
 
304
396
 
305
- def benchmark(directory: Path) -> None:
397
+ def benchmark(path: Path) -> None:
306
398
  console.log("[bold]Running benchmarks for Advent of Code[/bold]\n")
307
-
308
- # Find all day files
309
- day_files = sorted(directory.glob("[0-9][0-9].py"))
399
+ if path.is_dir():
400
+ day_files = sorted(path.glob("[0-9][0-9]*.py"))
401
+ else:
402
+ day_files = [Path(path)] if path.exists() else []
310
403
  if not day_files:
311
404
  console.log("[yellow]No day files found[/yellow]")
312
405
  return
@@ -354,14 +447,17 @@ def benchmark(directory: Path) -> None:
354
447
  )
355
448
  )
356
449
 
357
- readme_path = directory / "README.md"
450
+ if path.is_dir():
451
+ readme_path = path / "README.md"
452
+ else:
453
+ readme_path = path.parent / "README.md"
358
454
  results_table = build_markdown_table(
359
455
  results, total_time=total_time, total_part_1=total_part_1, total_part_2=total_part_2
360
456
  )
361
- update_readme(readme_path, results_table)
457
+ update_readme(readme_path, results_table, path)
362
458
 
363
459
 
364
- def run(filepath: Path) -> None:
460
+ def run(filepath: Path, benchmark: bool = False) -> None: # noqa: FBT001, FBT002
365
461
  # Import the python module on path
366
462
  if not filepath.exists():
367
463
  console.log(f"[red]File {filepath} does not exist[/red]")
@@ -375,21 +471,37 @@ def run(filepath: Path) -> None:
375
471
  module = importlib.util.module_from_spec(spec)
376
472
  spec.loader.exec_module(module)
377
473
 
378
- aoc = AoC(part_1=module.part1, part_2=module.part2, day=int(filepath.stem), year=AOC_YEAR)
474
+ # Match the first two digits and use them as the day number
475
+ # Assuming the files are named like 01.py, 02-alternative.py, 02-alternative2.py, etc.
476
+ match = re.match(r"(\d\d)", filepath.stem)
477
+ if not match:
478
+ return
479
+ aoc = AoC(
480
+ part_1=module.part1,
481
+ part_2=module.part2,
482
+ day=int(match.group(1)),
483
+ year=AOC_YEAR,
484
+ )
379
485
  if hasattr(module, "part1_asserts"):
380
486
  for test_input, expected in module.part1_asserts:
381
487
  aoc.assert_p1(test_input, expected)
382
488
  else:
383
489
  console.log("[yellow]No part 1 assertions found[/yellow]\n")
384
490
 
385
- aoc.submit_p1()
491
+ if benchmark:
492
+ aoc.submit_p1_benchmark()
493
+ else:
494
+ aoc.submit_p1()
386
495
  if hasattr(module, "part2_asserts"):
387
496
  for test_input, expected in module.part2_asserts:
388
497
  aoc.assert_p2(test_input, expected)
389
498
  else:
390
499
  console.log("[yellow]No part 2 assertions found[/yellow]\n")
391
500
 
392
- aoc.submit_p2()
501
+ if benchmark:
502
+ aoc.submit_p2_benchmark()
503
+ else:
504
+ aoc.submit_p2()
393
505
 
394
506
 
395
507
  def main() -> None:
@@ -439,8 +551,9 @@ def main() -> None:
439
551
  formatter_class=argparse.RawDescriptionHelpFormatter,
440
552
  epilog=dedent("""\
441
553
  Examples:
442
- adventofcode benchmark # Run benchmarks in current directory
443
- adventofcode benchmark ./2024 # Run benchmarks in the ./2024 directory
554
+ adventofcode benchmark # Run benchmarks in current directory
555
+ adventofcode benchmark -d ./2024 # Run benchmarks in the ./2024 directory
556
+ adventofcode benchmark -d ./2024 2 # Run benchmarks in the ./2024 directory for day 2 only
444
557
 
445
558
  The benchmark will:
446
559
  1. Find all day files (01.py, 02.py, etc.)
@@ -455,11 +568,11 @@ def main() -> None:
455
568
  """),
456
569
  )
457
570
  benchmark_parser.add_argument(
458
- "directory",
571
+ "path",
459
572
  type=Path,
460
573
  nargs="?",
461
574
  default=Path("."),
462
- help="Directory containing day files (default: current directory)",
575
+ help="Path where benchmarked file(s) are located (default: current directory)",
463
576
  )
464
577
 
465
578
  # Run Command
@@ -473,6 +586,13 @@ def main() -> None:
473
586
  adventofcode run 01.py # Run day 1 solution in current directory
474
587
  """),
475
588
  )
589
+ run_parser.add_argument(
590
+ "-b",
591
+ "--benchmark",
592
+ action="store_true",
593
+ help="Benchmark each part with Time.autorange()",
594
+ default=False,
595
+ )
476
596
  run_parser.add_argument(
477
597
  "filepath",
478
598
  type=Path,
@@ -485,9 +605,9 @@ def main() -> None:
485
605
  case "init":
486
606
  init_templates(args.year, args.directory, 12 if args.year >= 2025 else 25)
487
607
  case "benchmark":
488
- benchmark(args.directory)
608
+ benchmark(args.path)
489
609
  case "run":
490
- run(args.filepath)
610
+ run(args.filepath, benchmark=args.benchmark)
491
611
  case _:
492
612
  parser.print_help()
493
613
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: adventofcode
3
- Version: 25.7
3
+ Version: 25.9
4
4
  Summary: Helper utilities for solving Advent of Code puzzles
5
5
  Project-URL: Documentation, https://github.com/anze3db/adventofcode#readme
6
6
  Project-URL: Issues, https://github.com/anze3db/adventofcode/issues
@@ -163,9 +163,13 @@ uv run adventofcode benchmark
163
163
 
164
164
  This will run each day's solution and parse the timing results from the output. The results will be printed to the console as well as added to your README.md.
165
165
 
166
- Example console output:
166
+ If you are in a hurry you can also benchmark a single day's solution with
167
167
 
168
+ ```shell
169
+ uv run adventofcode benchmark 05.py
170
+ ```
168
171
 
172
+ Example console output:
169
173
 
170
174
  Example README:
171
175
 
@@ -0,0 +1,9 @@
1
+ adventofcode/__about__.py,sha256=4A9XMPg86X1WS9nqabg9JCJF6NklftkWEe4gQfoHIek,21
2
+ adventofcode/__init__.py,sha256=JRWxftg5aZS5lArASJk9icNYIIaqgAOQ_bZO4hzmT1E,6172
3
+ adventofcode/cli.py,sha256=CcQuKB07PfoQr6fYtIfHchV6MPJsFU6D1md0knFuzVk,21316
4
+ adventofcode/utils.py,sha256=QJ2AanjoNt_yVI8VZM9plrl9cpHsEhl29NyA4Aqs8Ug,258
5
+ adventofcode-25.9.dist-info/METADATA,sha256=3ZLhEnexvPWQ-EK5yoniAfyvPT9x-jCiVfeSqFkhJes,7772
6
+ adventofcode-25.9.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
7
+ adventofcode-25.9.dist-info/entry_points.txt,sha256=Yw9pyDrVVS3XWRcjOv1BnAxkqtJdYoG747A1LysScak,83
8
+ adventofcode-25.9.dist-info/licenses/LICENSE,sha256=7w16SgIHVGYHh8TS_-XnKFvY6aKa_JDtVFoduWtIPTY,1069
9
+ adventofcode-25.9.dist-info/RECORD,,
@@ -1,9 +0,0 @@
1
- adventofcode/__about__.py,sha256=6LsH-Sgy6mnAoxnUIsqchfv0y4jgogxX3Ct9FrLWQz0,21
2
- adventofcode/__init__.py,sha256=Lyu-evu1YGwV94SThnt6-Bo4JP82Vt3JNRrCyjDd7w0,5533
3
- adventofcode/cli.py,sha256=Ufj65ULzr_fz0l0NdnAVnIKcFgHAfP6LsRCWVd14qZ0,16422
4
- adventofcode/utils.py,sha256=QJ2AanjoNt_yVI8VZM9plrl9cpHsEhl29NyA4Aqs8Ug,258
5
- adventofcode-25.7.dist-info/METADATA,sha256=QDg55PI2ex8HyHPCoAAh2uQq8QcgnisihqC1_Im3atA,7649
6
- adventofcode-25.7.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
7
- adventofcode-25.7.dist-info/entry_points.txt,sha256=Yw9pyDrVVS3XWRcjOv1BnAxkqtJdYoG747A1LysScak,83
8
- adventofcode-25.7.dist-info/licenses/LICENSE,sha256=7w16SgIHVGYHh8TS_-XnKFvY6aKa_JDtVFoduWtIPTY,1069
9
- adventofcode-25.7.dist-info/RECORD,,