adventofcode 23.0b1__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.
@@ -0,0 +1 @@
1
+ __version__ = "23.0b1"
@@ -0,0 +1,183 @@
1
+ import datetime
2
+ import os
3
+ import re
4
+ import sys
5
+ import time
6
+ from contextlib import contextmanager
7
+ from pathlib import Path
8
+ from typing import Any, Callable
9
+
10
+ import percache
11
+ import requests
12
+ from bs4 import BeautifulSoup
13
+ from dotenv import load_dotenv
14
+ from rich.console import Console
15
+
16
+ load_dotenv()
17
+ cache = percache.Cache(".cache", livesync=True)
18
+ console = Console()
19
+
20
+ AOC_URL = "https://adventofcode.com"
21
+
22
+
23
+ AOC_SESSION = os.getenv("AOC_SESSION")
24
+
25
+ AOC_NOT_SET_MSG = (
26
+ "Set AOC_SESSION env variable to your session cookie on adventofcode.com (export AOC_SESSION='your session cookie')"
27
+ )
28
+
29
+
30
+ @contextmanager
31
+ def print_perf(typ=""):
32
+ t0 = time.perf_counter()
33
+ yield
34
+ diff = time.perf_counter() - t0
35
+ console.log(f"{diff:.5f}s for {typ}")
36
+
37
+
38
+ class AoC:
39
+ def __init__(
40
+ self,
41
+ day: int | None = None,
42
+ year: int | None = None,
43
+ *,
44
+ part_1: Callable[[list[str]], Any] | None = None,
45
+ part_2: Callable[[list[str]], Any] | None = None,
46
+ part_1_no_splitlines: Callable[[str], Any] | None = None,
47
+ part_2_no_splitlines: Callable[[str], Any] | None = None,
48
+ ):
49
+ if day is None:
50
+ current_filename = Path(sys.argv[0]).stem
51
+ current_filename_numbers = re.sub(r"[^0-9.]", "", current_filename)
52
+ day = int(current_filename_numbers)
53
+ if year is None:
54
+ year = datetime.datetime.now(tz=datetime.timezone.utc).year
55
+
56
+ console.log(f"Solving {day=} {year=}")
57
+ self.day = day
58
+ self.year = year
59
+ self.part_1 = part_1
60
+ self.part_2 = part_2
61
+ self.part_1_no_splitlines = part_1_no_splitlines
62
+ self.part_2_no_splitlines = part_2_no_splitlines
63
+
64
+ def print_p1(self):
65
+ console.log(get_puzzle(self.day, self.year, part=1))
66
+
67
+ def print_p2(self):
68
+ console.log(get_puzzle(self.day, self.year, part=2))
69
+
70
+ def get_input(self):
71
+ return get_input(year=self.year, day=self.day).splitlines()
72
+
73
+ def get_input_no_splitlines(self):
74
+ return get_input(year=self.year, day=self.day)
75
+
76
+ def assert_p1(self, inp: str, expected: Any):
77
+ if self.part_1 is None and self.part_1_no_splitlines is None:
78
+ msg = "Set part_1 when initializing AoC()"
79
+ raise Exception(msg)
80
+
81
+ res = None
82
+ with print_perf("assert_p1"):
83
+ if self.part_1 is not None:
84
+ res = self.part_1(inp.splitlines())
85
+ elif self.part_1_no_splitlines is not None:
86
+ res = self.part_1_no_splitlines(inp)
87
+
88
+ assert res is not None, "Result of part_1 should not be None"
89
+ assert res == expected, f"{res} != {expected}"
90
+
91
+ def assert_p2(self, inp: str, expected: Any):
92
+ if self.part_2 is None and self.part_2_no_splitlines is None:
93
+ msg = "Set part_2 when initializing AoC()"
94
+ raise Exception(msg)
95
+
96
+ res = None
97
+ with print_perf("assert_p2"):
98
+ if self.part_2 is not None:
99
+ res = self.part_2(inp.splitlines())
100
+ elif self.part_2_no_splitlines is not None:
101
+ res = self.part_2_no_splitlines(inp)
102
+
103
+ assert res is not None, "Result of part_2 should not be None"
104
+ assert res == expected, f"{res} != {expected}"
105
+
106
+ def submit_p1(self, answer: Any | None = None):
107
+ if answer is not None:
108
+ ...
109
+ elif self.part_1 is not None:
110
+ inp = self.get_input()
111
+ with print_perf("submit_p1"):
112
+ answer = self.part_1(inp)
113
+ elif self.part_1_no_splitlines is not None:
114
+ inp = self.get_input_no_splitlines()
115
+ with print_perf("submit_p1"):
116
+ answer = self.part_1_no_splitlines(inp)
117
+
118
+ submit(year=self.year, day=self.day, level=1, answer=answer)
119
+
120
+ def submit_p2(self, answer: Any | None = None):
121
+ if answer is not None:
122
+ ...
123
+ elif self.part_2 is not None:
124
+ inp = self.get_input()
125
+ with print_perf("submit_p2"):
126
+ answer = self.part_2(inp)
127
+ elif self.part_2_no_splitlines is not None:
128
+ inp = self.get_input_no_splitlines()
129
+ with print_perf("submit_p2"):
130
+ answer = self.part_2_no_splitlines(inp)
131
+
132
+ submit(year=self.year, day=self.day, level=2, answer=answer)
133
+
134
+
135
+ @cache
136
+ def get_puzzle(day: int, year: int, part: int) -> str:
137
+ console.log("Fetching puzzle text from server")
138
+ result = requests.get(
139
+ f"{AOC_URL}/{year}/day/{day}",
140
+ cookies={"session": AOC_SESSION} if AOC_SESSION else None,
141
+ timeout=10,
142
+ )
143
+ assert result.status_code == 200, result.text
144
+
145
+ soup = BeautifulSoup(result.text, features="html.parser")
146
+
147
+ index = part - 1
148
+ if len(soup.body.main.findAll("article")) < index:
149
+ return f"Part {part} Not yet available"
150
+
151
+ return soup.body.main.findAll("article")[part - 1].get_text()
152
+
153
+
154
+ @cache
155
+ def get_input(year: int, day: int) -> str:
156
+ assert AOC_SESSION, AOC_NOT_SET_MSG
157
+ console.log("Fetching from server")
158
+ result = requests.get(
159
+ f"{AOC_URL}/{year}/day/{day}/input",
160
+ cookies={"session": AOC_SESSION},
161
+ timeout=10,
162
+ )
163
+ assert result.status_code == 200, (f"{AOC_URL}/{year}/day/{day}/input", result.text)
164
+
165
+ return result.text
166
+
167
+
168
+ @cache
169
+ def submit(year: int, day: int, level: int, answer: Any):
170
+ assert AOC_SESSION, AOC_NOT_SET_MSG
171
+ console.log(f"Posting [bold]{answer}[/bold] for {day=} {level=}")
172
+ if not answer:
173
+ console.log("Skipping submission", answer)
174
+ return
175
+ result = requests.post(
176
+ f"{AOC_URL}/{year}/day/{day}/answer",
177
+ {"level": level, "answer": answer},
178
+ cookies={"session": AOC_SESSION},
179
+ timeout=10,
180
+ )
181
+ assert result.status_code == 200, result.text
182
+ soup = BeautifulSoup(result.text, features="html.parser")
183
+ console.log(soup.body.main.article.get_text())
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.1
2
+ Name: adventofcode
3
+ Version: 23.0b1
4
+ Summary: Helper utilities for solving Advent of Code puzzles
5
+ Project-URL: Documentation, https://github.com/anze3db/adventofcode#readme
6
+ Project-URL: Issues, https://github.com/anze3db/adventofcode/issues
7
+ Project-URL: Source, https://github.com/anze3db/adventofcode
8
+ Project-URL: Mastodon, https://fosstodon.org/@anze3db
9
+ Project-URL: Twitter, https://twitter.com/anze3db
10
+ Author-email: Anže Pečar <anze@pecar.me>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Requires-Python: >=3.8
23
+ Requires-Dist: beautifulsoup4
24
+ Requires-Dist: percache
25
+ Requires-Dist: python-dotenv
26
+ Requires-Dist: requests
27
+ Requires-Dist: rich
28
+ Description-Content-Type: text/markdown
29
+
30
+ # adventofcode
31
+
32
+ Helper utilities for solving Advent of Code puzzles.
33
+
34
+ * No copy-pasting puzzle inputs into files.
35
+ * No need to use low-level file APIs to read your inputs.
36
+ * Performance reports for example inputs and puzzle inputs.
37
+ * Submit the answer immediately when your code returns the result 🏎️
38
+
39
+ ## Usage
40
+
41
+ ### Install the package
42
+
43
+ Install the package with pip:
44
+ ```bash
45
+ pip install adventofcode
46
+ ```
47
+
48
+ ### Set your session cookie
49
+
50
+ Add the [adventofcode.com](https://adventofcode.com) session cookie value to your env:
51
+
52
+ ```bash
53
+ export AOC_SESSION="..."
54
+ ```
55
+
56
+ Alternatively, you can save your `AOC_SESSION="******"` value in a `.env` file.
57
+
58
+ > [!NOTE]
59
+ > Setting AOC_SESSION will allow you to get your personal puzzle output (`aoc.get_input()`) and submit your answers with `aoc.submit_p1()` and `aoc.submit_p2()`.
60
+
61
+ ### Use a template to solve puzzles
62
+
63
+ I use the following template to start solving puzzles, see my examples in [my repo for 2023](https://github.com/anze3db/adventofcode2023).
64
+
65
+ ```python
66
+ from adventofcode import AoC
67
+
68
+
69
+ def part1(inp):
70
+ return None
71
+
72
+
73
+ def part2(inp):
74
+ return None
75
+
76
+
77
+ aoc = AoC(part_1=part1, part_2=part2)
78
+ inp = """sample input"""
79
+ # Run your part1 function with sample input and assert the expected result:
80
+ aoc.assert_p1(inp, 42)
81
+ # Run your part1 function on puzzle input and submit the answer returned:
82
+ aoc.submit_p1()
83
+
84
+ # Run your part2 function with sample input and assert the expected result:
85
+ aoc.assert_p2(inp, 6*7)
86
+ # Run your part2 function on puzzle input and submit the answer returned:
87
+ aoc.submit_p2()
88
+ ```
89
+
90
+ > [!NOTE]
91
+ > All submissions and fetched results are cached locally in the `.cache.db` file so that we don't spam the AoC servers or resubmit the same answer multiple times.
92
+
93
+ ### Or build your workflow using the AoC class
94
+
95
+ ```python
96
+ from adventofcode import AoC
97
+
98
+ aoc = AoC() # defaults to current year and parses the day from the filename (e.g. 01.py will be day 1)
99
+
100
+ aoc.print_p1() # prints the first part of the puzzle
101
+ inp = aoc.get_input() # returns the input as a string
102
+ # solve the puzzle here
103
+ ...
104
+ aoc.submit_p1('part 1 answer') # submits the answer to the first part of the puzzle
105
+ aoc.print_p2() # prints the second part of the puzzle
106
+ # solve the puzzle here
107
+ ...
108
+ aoc.submit_p2('part 2 answer') # submits the answer to the second part of the puzzle
109
+ ```
@@ -0,0 +1,6 @@
1
+ adventofcode/__about__.py,sha256=ZAcaV0jlGn0EUKEFaJWWkIfUqBQMV2rKdxT0lspLZgI,23
2
+ adventofcode/__init__.py,sha256=rt2V1x3UUYXgBT0Utty_rlCBONvik3fnU_Qy-3eHLYw,5871
3
+ adventofcode-23.0b1.dist-info/METADATA,sha256=fEZEgPykLhcjilcogeadva4OV_DQ4RpyGJOIRAu-4gM,3495
4
+ adventofcode-23.0b1.dist-info/WHEEL,sha256=rKV0FgtKSxe-Q3jTBlmgn27qdhTm0_K1YKwPwAPskZ0,87
5
+ adventofcode-23.0b1.dist-info/licenses/LICENSE,sha256=7w16SgIHVGYHh8TS_-XnKFvY6aKa_JDtVFoduWtIPTY,1069
6
+ adventofcode-23.0b1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.20.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Anže Pečar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.