advoco 0.3.0__tar.gz
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.
- advoco-0.3.0/PKG-INFO +110 -0
- advoco-0.3.0/README.md +94 -0
- advoco-0.3.0/advoco/__init__.py +9 -0
- advoco-0.3.0/advoco/cache.py +75 -0
- advoco-0.3.0/advoco/cli.py +117 -0
- advoco-0.3.0/advoco/config.py +70 -0
- advoco-0.3.0/advoco/connect.py +66 -0
- advoco-0.3.0/advoco/do.py +157 -0
- advoco-0.3.0/advoco/exceptions.py +26 -0
- advoco-0.3.0/advoco/live.py +48 -0
- advoco-0.3.0/advoco/sample.py +78 -0
- advoco-0.3.0/advoco/tests/__init__.py +0 -0
- advoco-0.3.0/advoco/tests/test_grid.py +194 -0
- advoco-0.3.0/advoco/tools/grid.py +146 -0
- advoco-0.3.0/pyproject.toml +29 -0
advoco-0.3.0/PKG-INFO
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: advoco
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Advent of Code helper library. There are many like it, but this one is mine.
|
|
5
|
+
Author: thetaxfraudguy
|
|
6
|
+
Author-email: 57653752+thetaxfraudguy@users.noreply.github.com
|
|
7
|
+
Requires-Python: >=3.11,<4.0
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
10
|
+
Requires-Dist: beautifulsoup4 (>=4.11.1,<5.0.0)
|
|
11
|
+
Requires-Dist: click (>=8.1.3,<9.0.0)
|
|
12
|
+
Requires-Dist: pytz (>=2022.6,<2023.0)
|
|
13
|
+
Requires-Dist: requests (>=2.28.1,<3.0.0)
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# Advoco
|
|
17
|
+
Advent of Code helper library - why not??
|
|
18
|
+
Dear future contributor traipsing through history,
|
|
19
|
+
this was when this was a private repo that me and a buddy were collaborating on.
|
|
20
|
+
If this README does not look more polished in the current version, hunt me down
|
|
21
|
+
and slap me.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
```bash
|
|
25
|
+
poetry install
|
|
26
|
+
```
|
|
27
|
+
I'm still working actively so do this often.
|
|
28
|
+
|
|
29
|
+
## tl;dr
|
|
30
|
+
Do this once a year:
|
|
31
|
+
```bash
|
|
32
|
+
advoco generate-year
|
|
33
|
+
```
|
|
34
|
+
Then grab your session cookie from AoC using browser tools and add it to the
|
|
35
|
+
environment as `AOC_TOKEN`. Put it in your `.bashrc` and never think about it
|
|
36
|
+
again (until next year). The session lasts like a month so you shouldn't have to
|
|
37
|
+
do this that often.
|
|
38
|
+
|
|
39
|
+
Then, every day, _from the directory created with the generate-year command_:
|
|
40
|
+
```bash
|
|
41
|
+
advoco generate -d <day you want to generate>
|
|
42
|
+
```
|
|
43
|
+
or if it's after midnight, AoC time (Eastern):
|
|
44
|
+
```bash
|
|
45
|
+
advoco generate
|
|
46
|
+
```
|
|
47
|
+
In the generated script file, you'll find a function for part1 and part2 of the
|
|
48
|
+
daily AoC puzzle. You'll also find a `transform` function. This function will act
|
|
49
|
+
on each _line_ of the input. For instance, input always comes in as a string, so
|
|
50
|
+
if you want your puzzle input to be a list of ints, do this:
|
|
51
|
+
```python
|
|
52
|
+
def transform(line):
|
|
53
|
+
return int(line)
|
|
54
|
+
```
|
|
55
|
+
The last thing you'll find in the script is the call to `advoco.do()`. It starts
|
|
56
|
+
out with `sample=True` and will therefore attempt to parse the sample input Eric
|
|
57
|
+
uses on the webpage of the daily puzzle. It'll throw an error and give you advice
|
|
58
|
+
if it can't find sample input. When you're ready to try your solutions on your
|
|
59
|
+
real input, remove the sample argument.
|
|
60
|
+
|
|
61
|
+
## Explanations
|
|
62
|
+
Some context...
|
|
63
|
+
|
|
64
|
+
### WTF is `do` doing?
|
|
65
|
+
When you call `do()`, advoco inspects the call stack for the file that called it.
|
|
66
|
+
It looks through that file (as a module, using `getattr`) for a few things:
|
|
67
|
+
* A `transform` func. If it doesn't find one, the default one is basically
|
|
68
|
+
`lambda x: return x`
|
|
69
|
+
* Some part functions, i.e. `part1`, `part2`
|
|
70
|
+
|
|
71
|
+
It gets the raw input for the puzzle you're working on (more on that below), runs
|
|
72
|
+
that through whatever transform it's using, then passes it as the arg to the `part`
|
|
73
|
+
functions it found in your script file.
|
|
74
|
+
|
|
75
|
+
Finally, it gets the result of your `part` function and prints it. It does not yet
|
|
76
|
+
attempt to submit the answer for you, and it may not do that ever (not sure yet).
|
|
77
|
+
|
|
78
|
+
### WHAT *YEAR* (AND DAY) IS IT???
|
|
79
|
+
Advoco needs to figure out which puzzle input to go get, both the puzzle year and
|
|
80
|
+
the puzzle day. To determine this - really in all instances where advoco needs to
|
|
81
|
+
figure out a year and/or day - the following order is honored:
|
|
82
|
+
1. Anything explicitly passed. If you pass a `day` or `year` arg to `do`, that is
|
|
83
|
+
what advoco is going to work with. End of discussion. Explicit declaration trumps
|
|
84
|
+
all.
|
|
85
|
+
2. The calling context. Where is `do` being called from? Where is a cli command
|
|
86
|
+
being invoked? If `do` is being called from a python file, and that file name contains
|
|
87
|
+
digits, those digits are assumed to represent the day you want to work on. Further,
|
|
88
|
+
if that python file lives in a directory whose name contains the regex `r"20\d{2}"`,
|
|
89
|
+
then that regex match is assumed to be the year. For cli invocations, the folder
|
|
90
|
+
== year convention holds, but the day is never inferred from calling context.
|
|
91
|
+
3. The current day and year, in the AoC timezone (America/New_York).
|
|
92
|
+
|
|
93
|
+
### Notes
|
|
94
|
+
This still assumes that we're gonna be working with a list of lines as our input.
|
|
95
|
+
I haven't yet figured out the best way to handle the case where you want the whole
|
|
96
|
+
damn input string as one blob. Good ideas are welcome here.
|
|
97
|
+
|
|
98
|
+
Any input fetched from the AoC site is cached in `~/.cache/advoco` to not pester
|
|
99
|
+
the site. The inputs, as far as I can tell, have never and will never change, so
|
|
100
|
+
there's no cache expiry mechanism.
|
|
101
|
+
|
|
102
|
+
The `generate-year` command creates a top level folder called `_localonly_2022`.
|
|
103
|
+
This is just so you can AoC from within the advoco repo without git stressing out.
|
|
104
|
+
When it's ready for prime time, I'll change it to make a `2022` directory.
|
|
105
|
+
|
|
106
|
+
## Contributing
|
|
107
|
+
Bug reports are awesome but if you see something and you know how to fix it, by
|
|
108
|
+
all means! Just make a new branch and open a PR. Hell, just push directly to main
|
|
109
|
+
if you're super confident.
|
|
110
|
+
|
advoco-0.3.0/README.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Advoco
|
|
2
|
+
Advent of Code helper library - why not??
|
|
3
|
+
Dear future contributor traipsing through history,
|
|
4
|
+
this was when this was a private repo that me and a buddy were collaborating on.
|
|
5
|
+
If this README does not look more polished in the current version, hunt me down
|
|
6
|
+
and slap me.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
```bash
|
|
10
|
+
poetry install
|
|
11
|
+
```
|
|
12
|
+
I'm still working actively so do this often.
|
|
13
|
+
|
|
14
|
+
## tl;dr
|
|
15
|
+
Do this once a year:
|
|
16
|
+
```bash
|
|
17
|
+
advoco generate-year
|
|
18
|
+
```
|
|
19
|
+
Then grab your session cookie from AoC using browser tools and add it to the
|
|
20
|
+
environment as `AOC_TOKEN`. Put it in your `.bashrc` and never think about it
|
|
21
|
+
again (until next year). The session lasts like a month so you shouldn't have to
|
|
22
|
+
do this that often.
|
|
23
|
+
|
|
24
|
+
Then, every day, _from the directory created with the generate-year command_:
|
|
25
|
+
```bash
|
|
26
|
+
advoco generate -d <day you want to generate>
|
|
27
|
+
```
|
|
28
|
+
or if it's after midnight, AoC time (Eastern):
|
|
29
|
+
```bash
|
|
30
|
+
advoco generate
|
|
31
|
+
```
|
|
32
|
+
In the generated script file, you'll find a function for part1 and part2 of the
|
|
33
|
+
daily AoC puzzle. You'll also find a `transform` function. This function will act
|
|
34
|
+
on each _line_ of the input. For instance, input always comes in as a string, so
|
|
35
|
+
if you want your puzzle input to be a list of ints, do this:
|
|
36
|
+
```python
|
|
37
|
+
def transform(line):
|
|
38
|
+
return int(line)
|
|
39
|
+
```
|
|
40
|
+
The last thing you'll find in the script is the call to `advoco.do()`. It starts
|
|
41
|
+
out with `sample=True` and will therefore attempt to parse the sample input Eric
|
|
42
|
+
uses on the webpage of the daily puzzle. It'll throw an error and give you advice
|
|
43
|
+
if it can't find sample input. When you're ready to try your solutions on your
|
|
44
|
+
real input, remove the sample argument.
|
|
45
|
+
|
|
46
|
+
## Explanations
|
|
47
|
+
Some context...
|
|
48
|
+
|
|
49
|
+
### WTF is `do` doing?
|
|
50
|
+
When you call `do()`, advoco inspects the call stack for the file that called it.
|
|
51
|
+
It looks through that file (as a module, using `getattr`) for a few things:
|
|
52
|
+
* A `transform` func. If it doesn't find one, the default one is basically
|
|
53
|
+
`lambda x: return x`
|
|
54
|
+
* Some part functions, i.e. `part1`, `part2`
|
|
55
|
+
|
|
56
|
+
It gets the raw input for the puzzle you're working on (more on that below), runs
|
|
57
|
+
that through whatever transform it's using, then passes it as the arg to the `part`
|
|
58
|
+
functions it found in your script file.
|
|
59
|
+
|
|
60
|
+
Finally, it gets the result of your `part` function and prints it. It does not yet
|
|
61
|
+
attempt to submit the answer for you, and it may not do that ever (not sure yet).
|
|
62
|
+
|
|
63
|
+
### WHAT *YEAR* (AND DAY) IS IT???
|
|
64
|
+
Advoco needs to figure out which puzzle input to go get, both the puzzle year and
|
|
65
|
+
the puzzle day. To determine this - really in all instances where advoco needs to
|
|
66
|
+
figure out a year and/or day - the following order is honored:
|
|
67
|
+
1. Anything explicitly passed. If you pass a `day` or `year` arg to `do`, that is
|
|
68
|
+
what advoco is going to work with. End of discussion. Explicit declaration trumps
|
|
69
|
+
all.
|
|
70
|
+
2. The calling context. Where is `do` being called from? Where is a cli command
|
|
71
|
+
being invoked? If `do` is being called from a python file, and that file name contains
|
|
72
|
+
digits, those digits are assumed to represent the day you want to work on. Further,
|
|
73
|
+
if that python file lives in a directory whose name contains the regex `r"20\d{2}"`,
|
|
74
|
+
then that regex match is assumed to be the year. For cli invocations, the folder
|
|
75
|
+
== year convention holds, but the day is never inferred from calling context.
|
|
76
|
+
3. The current day and year, in the AoC timezone (America/New_York).
|
|
77
|
+
|
|
78
|
+
### Notes
|
|
79
|
+
This still assumes that we're gonna be working with a list of lines as our input.
|
|
80
|
+
I haven't yet figured out the best way to handle the case where you want the whole
|
|
81
|
+
damn input string as one blob. Good ideas are welcome here.
|
|
82
|
+
|
|
83
|
+
Any input fetched from the AoC site is cached in `~/.cache/advoco` to not pester
|
|
84
|
+
the site. The inputs, as far as I can tell, have never and will never change, so
|
|
85
|
+
there's no cache expiry mechanism.
|
|
86
|
+
|
|
87
|
+
The `generate-year` command creates a top level folder called `_localonly_2022`.
|
|
88
|
+
This is just so you can AoC from within the advoco repo without git stressing out.
|
|
89
|
+
When it's ready for prime time, I'll change it to make a `2022` directory.
|
|
90
|
+
|
|
91
|
+
## Contributing
|
|
92
|
+
Bug reports are awesome but if you see something and you know how to fix it, by
|
|
93
|
+
all means! Just make a new branch and open a PR. Hell, just push directly to main
|
|
94
|
+
if you're super confident.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Callable
|
|
5
|
+
|
|
6
|
+
ADVOCO_CACHE_DIR = Path.home() / ".cache" / "advoco"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def try_cache(fname: str, use_part_num: bool = False) -> Callable:
|
|
10
|
+
def decorator(func: Callable) -> Callable:
|
|
11
|
+
@functools.wraps(func)
|
|
12
|
+
def wrapper(year: str, day: str, *args, **kwargs) -> str:
|
|
13
|
+
if use_part_num:
|
|
14
|
+
part_num = args[0]
|
|
15
|
+
filename = f"{part_num}_{fname}"
|
|
16
|
+
else:
|
|
17
|
+
filename = fname
|
|
18
|
+
cache_file = ADVOCO_CACHE_DIR / year / day / filename
|
|
19
|
+
if cache_file.exists():
|
|
20
|
+
with open(cache_file, "r") as infile:
|
|
21
|
+
return infile.read()
|
|
22
|
+
else:
|
|
23
|
+
fetched_input = func(year, day, *args, **kwargs)
|
|
24
|
+
cache_file.parent.mkdir(exist_ok=True, parents=True)
|
|
25
|
+
with open(cache_file, "w") as outfile:
|
|
26
|
+
outfile.write(fetched_input)
|
|
27
|
+
return fetched_input
|
|
28
|
+
|
|
29
|
+
return wrapper
|
|
30
|
+
|
|
31
|
+
return decorator
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_cache(year: str, day: str):
|
|
35
|
+
cache_file = ADVOCO_CACHE_DIR / year / day / "cache.json"
|
|
36
|
+
if cache_file.exists():
|
|
37
|
+
with open(cache_file, "r") as infile:
|
|
38
|
+
return json.load(infile)
|
|
39
|
+
else:
|
|
40
|
+
return {}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def put_cache(year: str, day: str, cache: dict):
|
|
44
|
+
cache_file = ADVOCO_CACHE_DIR / year / day / "cache.json"
|
|
45
|
+
with open(cache_file, "w") as outfile:
|
|
46
|
+
outfile.write(json.dumps(cache))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def clear_cache(year: str = "", day: str = ""):
|
|
50
|
+
if day and not year:
|
|
51
|
+
raise ValueError(
|
|
52
|
+
"You gave me a day and no year and that confuses me! Argle bargle!!"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
to_clear = ADVOCO_CACHE_DIR
|
|
56
|
+
|
|
57
|
+
if year:
|
|
58
|
+
to_clear = to_clear / year
|
|
59
|
+
|
|
60
|
+
if day:
|
|
61
|
+
to_clear = to_clear / day
|
|
62
|
+
|
|
63
|
+
if to_clear.exists():
|
|
64
|
+
rmdir(to_clear)
|
|
65
|
+
print(f"Cache entries at {to_clear} deleted")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def rmdir(directory: Path) -> None:
|
|
69
|
+
directory = Path(directory)
|
|
70
|
+
for item in directory.iterdir():
|
|
71
|
+
if item.is_dir():
|
|
72
|
+
rmdir(item)
|
|
73
|
+
else:
|
|
74
|
+
item.unlink()
|
|
75
|
+
directory.rmdir()
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
import click
|
|
4
|
+
|
|
5
|
+
from advoco import __version__
|
|
6
|
+
from advoco.cache import clear_cache
|
|
7
|
+
from advoco.config import resolve_day_and_year, get_active_part
|
|
8
|
+
from advoco.live import get_live_input
|
|
9
|
+
from advoco.sample import get_sample_answer, get_sample_input
|
|
10
|
+
|
|
11
|
+
SCRIPT_CONTENT = """import advoco
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def transform(line):
|
|
15
|
+
return line
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def part1(inp):
|
|
19
|
+
return "Not implemented"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def part2(inp):
|
|
23
|
+
return "Not implemented"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
advoco.do()
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@click.group()
|
|
31
|
+
@click.version_option(version=__version__, prog_name="Advoco")
|
|
32
|
+
def cli():
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@click.command(name="generate", short_help="Generate python file for day")
|
|
37
|
+
@click.option("-d", "--day", help="Day to generate")
|
|
38
|
+
@click.option("--output-file", help="Name of file to which to write script")
|
|
39
|
+
def generate(day, output_file):
|
|
40
|
+
if not output_file:
|
|
41
|
+
context = Path.cwd()
|
|
42
|
+
day, _ = resolve_day_and_year(context, day=day)
|
|
43
|
+
output_file = f"{day}.py"
|
|
44
|
+
|
|
45
|
+
if not Path(output_file).exists() or click.confirm(
|
|
46
|
+
f"{output_file} already exists! Overwrite?"
|
|
47
|
+
):
|
|
48
|
+
with open(output_file, "w") as outfile:
|
|
49
|
+
outfile.write(SCRIPT_CONTENT)
|
|
50
|
+
|
|
51
|
+
click.echo(f"Script written to {output_file}. Happy adventing!")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@click.command(name="generate-year", short_help="Generate folder structure for year")
|
|
55
|
+
@click.option("--folder-name", help="Name of folder to generate")
|
|
56
|
+
@click.option("-y", "--year", help="Year to generate folder for")
|
|
57
|
+
def generate_year(folder_name, year):
|
|
58
|
+
context = Path.cwd()
|
|
59
|
+
_, year = resolve_day_and_year(context, year=year, day="1")
|
|
60
|
+
folder_name = folder_name or year
|
|
61
|
+
|
|
62
|
+
day_one = context / folder_name / "1.py"
|
|
63
|
+
day_one.parent.mkdir()
|
|
64
|
+
|
|
65
|
+
with open(day_one, "w") as outfile:
|
|
66
|
+
outfile.write(SCRIPT_CONTENT)
|
|
67
|
+
|
|
68
|
+
click.echo(f"New year folder created at ./{folder_name}")
|
|
69
|
+
click.echo(f"First day's script written to ./{folder_name}/1.py")
|
|
70
|
+
click.echo("Happy Adventing!")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@click.command(name="input", short_help="Get input")
|
|
74
|
+
@click.option("-d", "--day", help="Day to fetch input for")
|
|
75
|
+
@click.option("-y", "--year", help="Year to fetch input for")
|
|
76
|
+
@click.option("-s", "--sample", is_flag=True, help="Fetch sample input")
|
|
77
|
+
def get_input(day, year, sample):
|
|
78
|
+
context = Path.cwd()
|
|
79
|
+
day, year = resolve_day_and_year(context, day=day, year=year)
|
|
80
|
+
raw_input = get_sample_input(year, day) if sample else get_live_input(year, day)
|
|
81
|
+
click.echo(raw_input)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@click.command(name="clear-cache", short_help="Delete cache entries")
|
|
85
|
+
@click.option("-d", "--day", default="", help="Delete this day's folder in cache")
|
|
86
|
+
@click.option("-y", "--year", default="", help="Delete this year's folder in cahce")
|
|
87
|
+
def clear_cache_cmd(day, year):
|
|
88
|
+
clear_cache(year, day)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@click.command(name="sample-output", short_help="Get sample output")
|
|
92
|
+
@click.option("-d", "--day", help="Day to fetch output for")
|
|
93
|
+
@click.option("-y", "--year", help="Year to fetch output for")
|
|
94
|
+
@click.option("-p", "--part", default="1", help="Puzzle part to fetch output for")
|
|
95
|
+
def sample_output(day, year, part):
|
|
96
|
+
context = Path.cwd()
|
|
97
|
+
day, year = resolve_day_and_year(context, day=day, year=year)
|
|
98
|
+
click.echo(get_sample_answer(year, day, part))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@click.command(name="status", short_help="View day status")
|
|
102
|
+
@click.option("-d", "--day", default="", help="Day to fetch status for")
|
|
103
|
+
@click.option("-y", "--year", default="", help="Year to fetch status for")
|
|
104
|
+
def status_cmd(day, year):
|
|
105
|
+
active_part = get_active_part(year, day)
|
|
106
|
+
if active_part == "-1":
|
|
107
|
+
click.echo(f"Congratulations! You've completed {year}, Day {day}")
|
|
108
|
+
else:
|
|
109
|
+
click.echo(f"You're working on Part {active_part} for {year}, Day {day}")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
cli.add_command(generate)
|
|
113
|
+
cli.add_command(generate_year)
|
|
114
|
+
cli.add_command(get_input)
|
|
115
|
+
cli.add_command(clear_cache_cmd)
|
|
116
|
+
cli.add_command(sample_output)
|
|
117
|
+
cli.add_command(status_cmd)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Optional, Tuple
|
|
5
|
+
|
|
6
|
+
import pytz
|
|
7
|
+
|
|
8
|
+
from .connect import send_request
|
|
9
|
+
from .exceptions import DateOutOfRangeError
|
|
10
|
+
|
|
11
|
+
AOC_TZ = pytz.timezone("America/New_York")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_day_from_context(context: Path) -> str:
|
|
15
|
+
if context.is_file() and context.suffix == ".py":
|
|
16
|
+
return "".join(filter(str.isdigit, context.stem))
|
|
17
|
+
else:
|
|
18
|
+
return ""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_year_from_context(context: Path) -> str:
|
|
22
|
+
context_dir = context.parent if context.is_file() else context
|
|
23
|
+
match = re.search(r"20\d{2}", context_dir.stem)
|
|
24
|
+
if match:
|
|
25
|
+
return match.group()
|
|
26
|
+
else:
|
|
27
|
+
return ""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve_day_and_year(
|
|
31
|
+
calling_context: Path, year: Optional[str] = None, day: Optional[str] = None
|
|
32
|
+
) -> Tuple[str, str]:
|
|
33
|
+
now = datetime.now(tz=AOC_TZ)
|
|
34
|
+
|
|
35
|
+
resolved_day = day or get_day_from_context(calling_context) or str(now.day)
|
|
36
|
+
resolved_year = year or get_year_from_context(calling_context) or str(now.year)
|
|
37
|
+
|
|
38
|
+
if int(resolved_day) not in range(1, 26):
|
|
39
|
+
raise DateOutOfRangeError(f"Day '{resolved_day}' falls outside of Advent!")
|
|
40
|
+
if int(resolved_year) < 2015:
|
|
41
|
+
raise DateOutOfRangeError(f"Year '{resolved_year}' is before AoC started")
|
|
42
|
+
|
|
43
|
+
return resolved_day, resolved_year
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def get_active_part(year: str, day: str) -> str:
|
|
47
|
+
"""
|
|
48
|
+
Return the status of the given year/day combo. Returns the puzzle part that is
|
|
49
|
+
currently active for that day. If the day is complete (both puzzle parts done),
|
|
50
|
+
returns "-1"
|
|
51
|
+
|
|
52
|
+
If the day is complete, a "day-success" classed `p` tag will exist on the page.
|
|
53
|
+
If there are two "day-desc" classed `article` tags, we're on part two.
|
|
54
|
+
Otherwise, we're on part 1
|
|
55
|
+
|
|
56
|
+
If you pass an invalid day, `send_request` will yell at you so no need to handle
|
|
57
|
+
here
|
|
58
|
+
"""
|
|
59
|
+
soup = send_request("get", year, day, mmm_soup=True)
|
|
60
|
+
|
|
61
|
+
if soup.find(
|
|
62
|
+
lambda tag: tag.name == "p" and tag.text.startswith("Both parts of this puzzle")
|
|
63
|
+
):
|
|
64
|
+
return "-1"
|
|
65
|
+
|
|
66
|
+
day_descs = soup.find_all("article", {"class": "day-desc"})
|
|
67
|
+
if len(day_descs) == 2:
|
|
68
|
+
return "2"
|
|
69
|
+
else:
|
|
70
|
+
return "1"
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
import os
|
|
3
|
+
from bs4 import BeautifulSoup
|
|
4
|
+
from typing import Optional, Dict, Any, overload, Literal
|
|
5
|
+
|
|
6
|
+
from .exceptions import NoTokenError
|
|
7
|
+
|
|
8
|
+
AOC_URL_TPL = "https://adventofcode.com/{year}/day/{day}"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_auth_cookie_from_env() -> dict:
|
|
12
|
+
try:
|
|
13
|
+
token = os.environ["AOC_TOKEN"]
|
|
14
|
+
except KeyError:
|
|
15
|
+
raise NoTokenError(
|
|
16
|
+
"No Advent of Code auth token in environment. Please set 'AOC_TOKEN'."
|
|
17
|
+
)
|
|
18
|
+
else:
|
|
19
|
+
return {"session": token}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@overload
|
|
23
|
+
def send_request(
|
|
24
|
+
method: str,
|
|
25
|
+
year: str,
|
|
26
|
+
day: str,
|
|
27
|
+
mmm_soup: Literal[True],
|
|
28
|
+
endpoint: Optional[str] = None,
|
|
29
|
+
body: Optional[dict] = None,
|
|
30
|
+
) -> BeautifulSoup:
|
|
31
|
+
...
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@overload
|
|
35
|
+
def send_request(
|
|
36
|
+
method: str,
|
|
37
|
+
year: str,
|
|
38
|
+
day: str,
|
|
39
|
+
mmm_soup: Literal[False] = False,
|
|
40
|
+
endpoint: Optional[str] = None,
|
|
41
|
+
body: Optional[dict] = None,
|
|
42
|
+
) -> str:
|
|
43
|
+
...
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def send_request(
|
|
47
|
+
method: str,
|
|
48
|
+
year: str,
|
|
49
|
+
day: str,
|
|
50
|
+
mmm_soup: bool = False,
|
|
51
|
+
endpoint: Optional[str] = None,
|
|
52
|
+
body: Optional[dict] = None,
|
|
53
|
+
) -> str | BeautifulSoup:
|
|
54
|
+
endpoint = endpoint or ""
|
|
55
|
+
url = AOC_URL_TPL.format(year=year, day=day) + endpoint
|
|
56
|
+
request_kwargs: Dict[str, Any] = {"cookies": get_auth_cookie_from_env()}
|
|
57
|
+
if body:
|
|
58
|
+
request_kwargs["data"] = body
|
|
59
|
+
|
|
60
|
+
resp = requests.request(method, url, **request_kwargs)
|
|
61
|
+
resp.raise_for_status()
|
|
62
|
+
|
|
63
|
+
if mmm_soup:
|
|
64
|
+
return BeautifulSoup(resp.content, "html.parser")
|
|
65
|
+
else:
|
|
66
|
+
return resp.text
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from copy import deepcopy
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Optional, Union
|
|
5
|
+
|
|
6
|
+
from .config import resolve_day_and_year, get_active_part
|
|
7
|
+
from .exceptions import PartNotDefined
|
|
8
|
+
from .exceptions import WrongAnswerMcFly
|
|
9
|
+
from .live import get_live_input, get_live_answer
|
|
10
|
+
from .sample import get_sample_input, get_sample_answer
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class do(object):
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
input_file: Optional[str] = None,
|
|
17
|
+
sample_input_file: Optional[str] = None,
|
|
18
|
+
year: Optional[str] = None,
|
|
19
|
+
day: Optional[str] = None,
|
|
20
|
+
sample_answers: Optional[list[Union[str, int]]] = None,
|
|
21
|
+
use_raw_input: bool = False,
|
|
22
|
+
confirm: bool = False,
|
|
23
|
+
no_check: bool = False,
|
|
24
|
+
):
|
|
25
|
+
frame = inspect.stack()[1]
|
|
26
|
+
self.caller = inspect.getmodule(frame[0])
|
|
27
|
+
|
|
28
|
+
self.day, self.year = resolve_day_and_year(
|
|
29
|
+
Path(frame.filename), year=year, day=day
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
self.transform_func = getattr(self.caller, "transform")
|
|
34
|
+
except AttributeError:
|
|
35
|
+
self.transform_func = self.default_transform
|
|
36
|
+
|
|
37
|
+
if input_file:
|
|
38
|
+
with open(input_file, "r") as infile:
|
|
39
|
+
self.input = infile.read()
|
|
40
|
+
else:
|
|
41
|
+
self.input = get_live_input(self.year, self.day)
|
|
42
|
+
|
|
43
|
+
if sample_input_file:
|
|
44
|
+
with open(sample_input_file, "r") as infile:
|
|
45
|
+
self.sample_input = infile.read()
|
|
46
|
+
else:
|
|
47
|
+
self.sample_input = get_sample_input(self.year, self.day)
|
|
48
|
+
|
|
49
|
+
self.active_part = get_active_part(self.year, self.day)
|
|
50
|
+
|
|
51
|
+
self.raw = use_raw_input
|
|
52
|
+
self.sample_answer_overrides = sample_answers or []
|
|
53
|
+
self.confirm = confirm
|
|
54
|
+
self.no_check = no_check
|
|
55
|
+
|
|
56
|
+
self.solve()
|
|
57
|
+
|
|
58
|
+
def solve(self):
|
|
59
|
+
if self.active_part == "1":
|
|
60
|
+
# we don't move on to part 2 in the same run...nobody's THAT good at AoC
|
|
61
|
+
self.do_part("1")
|
|
62
|
+
else:
|
|
63
|
+
self.do_part("1")
|
|
64
|
+
self.do_part("2")
|
|
65
|
+
|
|
66
|
+
def do_part(self, part_num: str):
|
|
67
|
+
sample_ans = self.get_answer(part_num, self.sample_input)
|
|
68
|
+
if self.no_check:
|
|
69
|
+
print(f"Part {part_num} (Sample):", sample_ans)
|
|
70
|
+
else:
|
|
71
|
+
sample_correct = self.get_sample_answer(part_num)
|
|
72
|
+
|
|
73
|
+
if str(sample_correct) != sample_ans:
|
|
74
|
+
raise WrongAnswerMcFly(
|
|
75
|
+
f"(Sample) - Expected '{sample_correct}' but got '{sample_ans}'"
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
print(f"Part {part_num} (Sample): '{sample_ans}' is the correct answer!")
|
|
79
|
+
|
|
80
|
+
live_ans = self.get_answer(part_num, self.input)
|
|
81
|
+
if self.no_check:
|
|
82
|
+
print(f"Part {part_num}: {live_ans}")
|
|
83
|
+
return
|
|
84
|
+
|
|
85
|
+
if self.active_part == part_num:
|
|
86
|
+
if not (self.confirm or lame_confirm(live_ans, part_num)):
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
live_correct = get_live_answer(self.year, self.day, part_num, live_ans)
|
|
90
|
+
if live_correct != live_ans:
|
|
91
|
+
raise WrongAnswerMcFly(f"Expected '{live_correct}' but got '{live_ans}'")
|
|
92
|
+
|
|
93
|
+
print(f"Part {part_num}: '{live_ans}' is the correct answer!")
|
|
94
|
+
|
|
95
|
+
def get_answer(self, part_num: str, raw_input: str) -> str:
|
|
96
|
+
if self.raw:
|
|
97
|
+
input_to_use = self.transform_func(raw_input)
|
|
98
|
+
else:
|
|
99
|
+
input_to_use = list(
|
|
100
|
+
map(lambda x: self.transform_func(x), raw_input.split("\n"))
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
ans = getattr(self.caller, f"part{part_num}")(deepcopy(input_to_use))
|
|
105
|
+
except AttributeError:
|
|
106
|
+
raise PartNotDefined(f"Part {part_num} is not defined!")
|
|
107
|
+
|
|
108
|
+
return str(ans)
|
|
109
|
+
|
|
110
|
+
def get_sample_answer(self, part_num):
|
|
111
|
+
try:
|
|
112
|
+
override = self.sample_answer_overrides[int(part_num) - 1]
|
|
113
|
+
if override:
|
|
114
|
+
return override
|
|
115
|
+
except IndexError:
|
|
116
|
+
pass
|
|
117
|
+
|
|
118
|
+
return get_sample_answer(self.year, self.day, part_num)
|
|
119
|
+
|
|
120
|
+
@staticmethod
|
|
121
|
+
def default_transform(raw_input):
|
|
122
|
+
return raw_input
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def do_offline(input_file: str, use_raw_input: bool = False) -> None:
|
|
126
|
+
frame = inspect.stack()[1]
|
|
127
|
+
caller = inspect.getmodule(frame[0])
|
|
128
|
+
|
|
129
|
+
with open(input_file, "r") as infile:
|
|
130
|
+
raw_input = infile.read()
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
transform_func = getattr(caller, "transform")
|
|
134
|
+
except AttributeError:
|
|
135
|
+
|
|
136
|
+
def transform_func(line):
|
|
137
|
+
return line
|
|
138
|
+
|
|
139
|
+
if use_raw_input:
|
|
140
|
+
input_to_use = transform_func(raw_input)
|
|
141
|
+
else:
|
|
142
|
+
input_to_use = list(map(lambda x: transform_func(x), raw_input.split("\n")))
|
|
143
|
+
|
|
144
|
+
for part in ["1", "2"]:
|
|
145
|
+
try:
|
|
146
|
+
ans = getattr(caller, f"part{part}")(deepcopy(input_to_use))
|
|
147
|
+
except AttributeError:
|
|
148
|
+
raise PartNotDefined(f"Part {part} is not defined!")
|
|
149
|
+
else:
|
|
150
|
+
print(f"Part {part} (Offline): {ans}")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def lame_confirm(ans: str, part_num: str) -> bool:
|
|
154
|
+
yes = {"yes", "y", "ye", ""}
|
|
155
|
+
prompt = f"Submit '{ans}' as your solution for part {part_num}? (y/n) "
|
|
156
|
+
|
|
157
|
+
return input(prompt).lower() in yes
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
class AdvocoException(Exception):
|
|
2
|
+
pass
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class NoTokenError(AdvocoException):
|
|
6
|
+
pass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class SampleTextNotFound(AdvocoException):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class DateOutOfRangeError(AdvocoException):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class WrongAnswerMcFly(AdvocoException):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PuzzleNotAvailableError(AdvocoException):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PartNotDefined(AdvocoException):
|
|
26
|
+
pass
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
from .cache import try_cache
|
|
4
|
+
from .connect import send_request
|
|
5
|
+
from .exceptions import WrongAnswerMcFly, PuzzleNotAvailableError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@try_cache("live_input.txt")
|
|
9
|
+
def get_live_input(year: str, day: str) -> str:
|
|
10
|
+
inp = send_request("get", year, day, endpoint="/input")
|
|
11
|
+
if inp.endswith("\n"):
|
|
12
|
+
return inp[:-1]
|
|
13
|
+
else:
|
|
14
|
+
return inp
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@try_cache("live_answer.txt", use_part_num=True)
|
|
18
|
+
def get_live_answer(year: str, day: str, part_num: str, ans: str) -> str:
|
|
19
|
+
body = {"answer": ans, "level": part_num}
|
|
20
|
+
soup = send_request("post", year, day, endpoint="/answer", body=body, mmm_soup=True)
|
|
21
|
+
|
|
22
|
+
message = soup.find("article")
|
|
23
|
+
if message:
|
|
24
|
+
if "That's the right answer" in message.text:
|
|
25
|
+
return ans
|
|
26
|
+
elif "Did you already complete it" in message.text:
|
|
27
|
+
old_answer = get_answer_from_puzzle_page(year, day, part_num)
|
|
28
|
+
if old_answer:
|
|
29
|
+
return old_answer
|
|
30
|
+
else:
|
|
31
|
+
raise WrongAnswerMcFly(message.text)
|
|
32
|
+
else:
|
|
33
|
+
raise WrongAnswerMcFly(message.text)
|
|
34
|
+
|
|
35
|
+
raise PuzzleNotAvailableError(
|
|
36
|
+
f"Tried to submit answer, but got a woogity response: {soup}"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def get_answer_from_puzzle_page(year: str, day: str, part_num: str) -> Optional[str]:
|
|
41
|
+
soup = send_request("get", year, day, mmm_soup=True)
|
|
42
|
+
answer_texts = soup.find_all(
|
|
43
|
+
lambda tag: tag.name == "p" and tag.text.startswith("Your puzzle answer was")
|
|
44
|
+
)
|
|
45
|
+
try:
|
|
46
|
+
return answer_texts[int(part_num) - 1].find("code").text
|
|
47
|
+
except IndexError:
|
|
48
|
+
return None
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from .cache import try_cache
|
|
2
|
+
from .connect import send_request
|
|
3
|
+
from .exceptions import SampleTextNotFound, PuzzleNotAvailableError
|
|
4
|
+
|
|
5
|
+
NO_SAMPLE_TPL = """
|
|
6
|
+
Could not find sample input for day {day}, {year}.
|
|
7
|
+
The sample input is probably there, we just couldn't parse the page and find it.
|
|
8
|
+
Go to the webpage and grab the sample input manually (or run `advoco input`!), then
|
|
9
|
+
save it to a file. You can pass that file to `advoco.do` like so:
|
|
10
|
+
|
|
11
|
+
advoco.do(input_file='path/to/input.txt')
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@try_cache("sample_input.txt")
|
|
16
|
+
def get_sample_input(year: str, day: str) -> str:
|
|
17
|
+
"""
|
|
18
|
+
Attempt to get puzzle test input from the text of the puzzle's webpage
|
|
19
|
+
Eric gives a sample input for each puzzle and goes over the expected output
|
|
20
|
+
using that sample.
|
|
21
|
+
|
|
22
|
+
Fortunately, he's pretty consistent with where that sample input shows up,
|
|
23
|
+
so we can take advantage and pull it down. The rules are as follows:
|
|
24
|
+
We look for a <p> tag whose text includes "example" and ":" (but not
|
|
25
|
+
necessarily "example:", sometimes he phrases it like, "For example,
|
|
26
|
+
consider the following input:").
|
|
27
|
+
|
|
28
|
+
We check the first such tag we find to see if it is followed by a <pre> tag
|
|
29
|
+
with a <code> tag child. If so, we can feel pretty good that the contents
|
|
30
|
+
of that <code> tag are our sample input.
|
|
31
|
+
"""
|
|
32
|
+
soup = send_request("get", year, day, mmm_soup=True)
|
|
33
|
+
|
|
34
|
+
paras = soup.find_all("p")
|
|
35
|
+
for para in paras:
|
|
36
|
+
para_text = para.get_text()
|
|
37
|
+
if "example" in para_text and ":" in para_text:
|
|
38
|
+
try:
|
|
39
|
+
candidate = para.fetchNextSiblings()[0]
|
|
40
|
+
except IndexError:
|
|
41
|
+
break
|
|
42
|
+
|
|
43
|
+
if candidate.name == "pre":
|
|
44
|
+
for child in candidate.children:
|
|
45
|
+
if child.name == "code":
|
|
46
|
+
# We can feel pretty good that this is it
|
|
47
|
+
sample_input = child.get_text()
|
|
48
|
+
# Sample input tends to have a spare '\n' at the end
|
|
49
|
+
if sample_input.endswith("\n"):
|
|
50
|
+
return sample_input[:-1]
|
|
51
|
+
else:
|
|
52
|
+
return sample_input
|
|
53
|
+
|
|
54
|
+
# We'd like to only check the first p tag with "example" and ":"
|
|
55
|
+
break
|
|
56
|
+
|
|
57
|
+
raise SampleTextNotFound(NO_SAMPLE_TPL.format(year=year, day=day))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@try_cache("sample_answer.txt", use_part_num=True)
|
|
61
|
+
def get_sample_answer(year: str, day: str, part: str) -> str:
|
|
62
|
+
soup = send_request("get", year, day, mmm_soup=True)
|
|
63
|
+
try:
|
|
64
|
+
problem_description = soup.find_all("article")[int(part) - 1]
|
|
65
|
+
except IndexError:
|
|
66
|
+
raise PuzzleNotAvailableError(
|
|
67
|
+
f"Part {part} of day {day}, {year} is not available"
|
|
68
|
+
)
|
|
69
|
+
ems = []
|
|
70
|
+
for code in problem_description.find_all("code"):
|
|
71
|
+
ems += code.find_all("em")
|
|
72
|
+
if ems:
|
|
73
|
+
return ems[-1].text
|
|
74
|
+
|
|
75
|
+
raise SampleTextNotFound(
|
|
76
|
+
f"Tried to parse the webpage for day {day}, {year} but "
|
|
77
|
+
"couldn't find the sample answer"
|
|
78
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from advoco.tools.grid import get_manhattan_dist, Vector
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
#################### get_manhattan_dist ####################
|
|
6
|
+
@pytest.mark.parametrize(
|
|
7
|
+
"tuple_a,tuple_b,expected",
|
|
8
|
+
[
|
|
9
|
+
((0, 0), (0, 0), 0),
|
|
10
|
+
((0, 0), (1, 1), 2),
|
|
11
|
+
((0, 0), (-1, -1), 2),
|
|
12
|
+
((0, 0), (5, -5), 10),
|
|
13
|
+
(
|
|
14
|
+
(5234701378045132, -1234701378045132),
|
|
15
|
+
(-5234701378045132, 4234701378045132),
|
|
16
|
+
15938805512180528,
|
|
17
|
+
),
|
|
18
|
+
],
|
|
19
|
+
)
|
|
20
|
+
def test_manhattan_dist(tuple_a, tuple_b, expected):
|
|
21
|
+
assert get_manhattan_dist(tuple_a, tuple_b) == expected
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
#################### Vector ####################
|
|
25
|
+
def test_different_vectors_do_not_equal():
|
|
26
|
+
assert Vector([0]) != Vector([1])
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@pytest.mark.parametrize(
|
|
30
|
+
"vector_a_inp,vector_b_inp,expected_sum_inp",
|
|
31
|
+
[
|
|
32
|
+
# Small numbers
|
|
33
|
+
([1, 2], [4, 10], [5, 12]),
|
|
34
|
+
# Negatives
|
|
35
|
+
([-5, 3], [2, -13], [-3, -10]),
|
|
36
|
+
# Big numbers
|
|
37
|
+
(
|
|
38
|
+
[111111111111111111111111111111, 222222222222222222222222222222],
|
|
39
|
+
[222222222222222222222222222222, 555555555555555555555555555555],
|
|
40
|
+
[333333333333333333333333333333, 777777777777777777777777777777],
|
|
41
|
+
),
|
|
42
|
+
# Dimensions > 2 (if we can do 2d and 10d, we can probably do n-d)
|
|
43
|
+
(
|
|
44
|
+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
|
|
45
|
+
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
|
|
46
|
+
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28],
|
|
47
|
+
),
|
|
48
|
+
],
|
|
49
|
+
)
|
|
50
|
+
def test_vectors_add_together(vector_a_inp, vector_b_inp, expected_sum_inp):
|
|
51
|
+
x = Vector(vector_a_inp)
|
|
52
|
+
y = Vector(vector_b_inp)
|
|
53
|
+
expected_sum = Vector(expected_sum_inp)
|
|
54
|
+
assert x + y == expected_sum
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@pytest.mark.parametrize(
|
|
58
|
+
"vector_a_inp,vector_b_inp,expected_diff_inp",
|
|
59
|
+
[
|
|
60
|
+
# Small numbers
|
|
61
|
+
([5, 3], [1, 3], [4, 0]),
|
|
62
|
+
# Negatives
|
|
63
|
+
([-5, 3], [2, -13], [-7, 16]),
|
|
64
|
+
# Big numbers
|
|
65
|
+
(
|
|
66
|
+
[111111111111111111111111111111, 222222222222222222222222222222],
|
|
67
|
+
[222222222222222222222222222222, 555555555555555555555555555555],
|
|
68
|
+
[-111111111111111111111111111111, -333333333333333333333333333333],
|
|
69
|
+
),
|
|
70
|
+
# Dimensions > 2 (if we can do 2d and 10d, we can probably do n-d)
|
|
71
|
+
(
|
|
72
|
+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
|
|
73
|
+
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
|
|
74
|
+
[-10, -10, -10, -10, -10, -10, -10, -10, -10, -10],
|
|
75
|
+
),
|
|
76
|
+
],
|
|
77
|
+
)
|
|
78
|
+
def test_vectors_subtract(vector_a_inp, vector_b_inp, expected_diff_inp):
|
|
79
|
+
x = Vector(vector_a_inp)
|
|
80
|
+
y = Vector(vector_b_inp)
|
|
81
|
+
expected_diff = Vector(expected_diff_inp)
|
|
82
|
+
assert x - y == expected_diff
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_vectors_subtract_both_directions():
|
|
86
|
+
"""Ensure that `x - y` is evaluated differently than `y - x`.
|
|
87
|
+
Background: __rsub__ and magic methods can get confusing, got worried
|
|
88
|
+
that `y - x` was flipping subtraction order. Turned out to not be true,
|
|
89
|
+
but it was only by testing that I fully understood things."""
|
|
90
|
+
x = Vector([5, 3])
|
|
91
|
+
y = Vector([4, -7])
|
|
92
|
+
expected_x_diff_y = Vector([1, 10])
|
|
93
|
+
assert x - y == expected_x_diff_y
|
|
94
|
+
expected_y_diff_x = Vector([-1, -10])
|
|
95
|
+
assert y - x == expected_y_diff_x
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_add_subtract_with_non_vector_raise():
|
|
99
|
+
vec_2d = Vector([1, 2])
|
|
100
|
+
tuple_2d = (3, 4)
|
|
101
|
+
# Need to ensure + in BOTH directions causes exception!
|
|
102
|
+
with pytest.raises(TypeError):
|
|
103
|
+
vec_2d + tuple_2d
|
|
104
|
+
with pytest.raises(TypeError):
|
|
105
|
+
tuple_2d + vec_2d
|
|
106
|
+
# Need to ensure - in BOTH directions causes exception!
|
|
107
|
+
with pytest.raises(TypeError):
|
|
108
|
+
vec_2d - tuple_2d
|
|
109
|
+
with pytest.raises(TypeError):
|
|
110
|
+
tuple_2d - vec_2d
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_vectors_of_different_lengths_raise():
|
|
114
|
+
vec_2d = Vector([1, 2])
|
|
115
|
+
vec_3d = Vector([1, 2, 3])
|
|
116
|
+
with pytest.raises(ValueError):
|
|
117
|
+
vec_2d + vec_3d
|
|
118
|
+
with pytest.raises(ValueError):
|
|
119
|
+
vec_2d - vec_3d
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@pytest.mark.parametrize(
|
|
123
|
+
"scalar,vector_inp,expected_product_inp",
|
|
124
|
+
[
|
|
125
|
+
# Small numbers
|
|
126
|
+
(-2, [-3, 5], [6, -10]),
|
|
127
|
+
# Big numbers
|
|
128
|
+
(
|
|
129
|
+
200000000000000000000,
|
|
130
|
+
[111111111111111111111111111111, 222222222222222222222222222222],
|
|
131
|
+
[
|
|
132
|
+
22222222222222222222222222222200000000000000000000,
|
|
133
|
+
44444444444444444444444444444400000000000000000000,
|
|
134
|
+
],
|
|
135
|
+
),
|
|
136
|
+
# Dimensions > 2 (if we can do 2d and 10d, we can probably do n-d)
|
|
137
|
+
(
|
|
138
|
+
3,
|
|
139
|
+
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
|
|
140
|
+
[30, 33, 36, 39, 42, 45, 48, 51, 54, 57],
|
|
141
|
+
),
|
|
142
|
+
],
|
|
143
|
+
)
|
|
144
|
+
def test_vectors_left_scalar_multiply(scalar, vector_inp, expected_product_inp):
|
|
145
|
+
x = Vector(vector_inp)
|
|
146
|
+
expected_product = Vector(expected_product_inp)
|
|
147
|
+
assert scalar * x == expected_product
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@pytest.mark.parametrize(
|
|
151
|
+
"scalar,vector_inp,expected_product_inp",
|
|
152
|
+
[
|
|
153
|
+
# Small numbers
|
|
154
|
+
(-2, [-3, 5], [6, -10]),
|
|
155
|
+
# Big numbers
|
|
156
|
+
(
|
|
157
|
+
200000000000000000000,
|
|
158
|
+
[111111111111111111111111111111, 222222222222222222222222222222],
|
|
159
|
+
[
|
|
160
|
+
22222222222222222222222222222200000000000000000000,
|
|
161
|
+
44444444444444444444444444444400000000000000000000,
|
|
162
|
+
],
|
|
163
|
+
),
|
|
164
|
+
# Dimensions > 2 (if we can do 2d and 10d, we can probably do n-d)
|
|
165
|
+
(
|
|
166
|
+
3,
|
|
167
|
+
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
|
|
168
|
+
[30, 33, 36, 39, 42, 45, 48, 51, 54, 57],
|
|
169
|
+
),
|
|
170
|
+
],
|
|
171
|
+
)
|
|
172
|
+
def test_vectors_right_scalar_multiply(scalar, vector_inp, expected_product_inp):
|
|
173
|
+
x = Vector(vector_inp)
|
|
174
|
+
expected_product = Vector(expected_product_inp)
|
|
175
|
+
assert x * scalar == expected_product
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def test_equal_vectors_hash_identically():
|
|
179
|
+
x_primus = Vector([2, 7])
|
|
180
|
+
x_secundus = Vector([2, 7])
|
|
181
|
+
assert hash(x_primus) == hash(x_secundus)
|
|
182
|
+
|
|
183
|
+
zero_vector = Vector([0, 0])
|
|
184
|
+
assert hash(x_primus - x_secundus) == hash(zero_vector)
|
|
185
|
+
|
|
186
|
+
# While we're thinking about hashing, verify dictionary access works too
|
|
187
|
+
d = {}
|
|
188
|
+
VALUE = "working as expected"
|
|
189
|
+
d[x_primus] = VALUE
|
|
190
|
+
assert d[x_secundus] == VALUE
|
|
191
|
+
assert d[x_primus] == d[x_secundus]
|
|
192
|
+
OTHER_VALUE = "still working as expected"
|
|
193
|
+
d[zero_vector] = OTHER_VALUE
|
|
194
|
+
assert d[x_primus - x_secundus] == OTHER_VALUE
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
from typing import List, Any, Callable, Tuple
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Vector(tuple):
|
|
5
|
+
"""Stores position info. Can do basic math. Usage: `Vector([4, 7])`.
|
|
6
|
+
|
|
7
|
+
Because this rides on top of `tuple` calls for doing instantiation,
|
|
8
|
+
you'll want to call it with an iterable . If you call it with positional
|
|
9
|
+
args, it will just break. [If we really want this API, it's doable, but
|
|
10
|
+
it requires understanding how to work with __new__, not just __init__.]
|
|
11
|
+
Examples:
|
|
12
|
+
+ Vector([4, 7])
|
|
13
|
+
+ Vector([1, -2, 3, -4, 5, -6, 7])
|
|
14
|
+
---BAD---> Vector(4, 7) <---WILL NOT WORK---
|
|
15
|
+
|
|
16
|
+
Math Example:
|
|
17
|
+
Vector([4, 7]) + Vector([6, 3]) - (10 * Vector([1, -1]))
|
|
18
|
+
produces ===> Vector([0, 20])
|
|
19
|
+
|
|
20
|
+
Intent is to have a way to record position, but also able to combine them.
|
|
21
|
+
Basically behaves the same as vectors from precalculus math class.
|
|
22
|
+
Can be arbitrary dimension, not just 2d.
|
|
23
|
+
Supports addition, subtraction, and **scalar** multiplication (can multiply
|
|
24
|
+
a Vector by a number, but can't multiply two Vectors). Most importantly,
|
|
25
|
+
it handles equality, hashing, and dictionary lookups as expected, since
|
|
26
|
+
that's what it's most likely to be used for.
|
|
27
|
+
|
|
28
|
+
There's some safety stuff in here -- we verify that lengths are the same
|
|
29
|
+
before adding, for example -- but it's not foolproof. For instance, you
|
|
30
|
+
could create a Vector from a string and it would merrily go on its way
|
|
31
|
+
because it's just a thin layer on top of `tuple`. I don't think it's worth
|
|
32
|
+
it to try to add a whole bunch more safety around verifying that the
|
|
33
|
+
incoming values are numbers, but I could be wrong.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __repr__(self):
|
|
37
|
+
"""Returns an actual `eval`-uable string, e.g: Vector([1, 2, 3])"""
|
|
38
|
+
# Approach kinda hacky, couldn't figure out a proper way to get values
|
|
39
|
+
# of tuple and make it look like a list, so just actually `list` it.
|
|
40
|
+
return f"Vector({list(self)})"
|
|
41
|
+
|
|
42
|
+
def __add__(self, other):
|
|
43
|
+
if not isinstance(other, Vector):
|
|
44
|
+
raise TypeError("Vectors can only add with other Vectors")
|
|
45
|
+
if len(self) != len(other):
|
|
46
|
+
raise ValueError("Can not add Vectors of different lengths")
|
|
47
|
+
return Vector([val[0] + val[1] for val in zip(self, other)])
|
|
48
|
+
|
|
49
|
+
def __radd__(self, other):
|
|
50
|
+
"""Takes over `other + self` direction. Ensure Vector primacy!"""
|
|
51
|
+
return self.__add__(other)
|
|
52
|
+
|
|
53
|
+
def __sub__(self, other):
|
|
54
|
+
if not isinstance(other, Vector):
|
|
55
|
+
raise TypeError("Vectors can only subtract with other Vectors")
|
|
56
|
+
if len(self) != len(other):
|
|
57
|
+
raise ValueError("Can not subtract Vectors of different lengths")
|
|
58
|
+
return Vector([val[0] - val[1] for val in zip(self, other)])
|
|
59
|
+
|
|
60
|
+
def __rsub__(self, other):
|
|
61
|
+
"""Takes over `other - self` direction. Ensure Vector primacy!
|
|
62
|
+
|
|
63
|
+
This is a bit confusing. If `x` and `y` are both vectors and
|
|
64
|
+
you want to evaluate `x - y`, in theory you should be able to do
|
|
65
|
+
`x.__sub__(y)` OR `y.__rsub__(x)` and get whatever `x - y` ought to
|
|
66
|
+
come out as. However, because __sub__ is implemented and both are
|
|
67
|
+
Vectors, Python would never call out to __rsub__ in that case.
|
|
68
|
+
Thus, __rsub__ would only get used if `x` was not actually a Vector,
|
|
69
|
+
but we just want an exception to get raised when `x` and `y` are not
|
|
70
|
+
both Vectors, so that's why this whole thing exists. I'm very, very
|
|
71
|
+
confident that the NotImplementedError will never happen, but that
|
|
72
|
+
sure will be interesting if it does!
|
|
73
|
+
|
|
74
|
+
Yeah, it's a bit silly. We could implement a `reverse` bool on __sub__
|
|
75
|
+
to handle this, but that's extra logic that would literally never get
|
|
76
|
+
used, so this seemed better. ¯\_(ツ)_/¯"""
|
|
77
|
+
if not isinstance(other, Vector):
|
|
78
|
+
raise TypeError("Vectors can only subtract with other Vectors")
|
|
79
|
+
else:
|
|
80
|
+
raise NotImplementedError("This code should never run. Whoops.")
|
|
81
|
+
|
|
82
|
+
def __mul__(self, other):
|
|
83
|
+
"""SCALAR multiplication. We do not implement anything else."""
|
|
84
|
+
return Vector([other * val for val in self])
|
|
85
|
+
|
|
86
|
+
def __rmul__(self, other):
|
|
87
|
+
"""Still just SCALAR multiplication. Handles the other * self side."""
|
|
88
|
+
return self.__mul__(other)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
GRID_DELTAS = [(0, 1), (0, -1), (1, 0), (-1, 0)]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def get_neighbors(
|
|
95
|
+
grid: List[list],
|
|
96
|
+
row: int,
|
|
97
|
+
col: int,
|
|
98
|
+
distance: int = 1,
|
|
99
|
+
gimme_indices: bool = False,
|
|
100
|
+
diagonals: bool = False,
|
|
101
|
+
) -> List[Any]:
|
|
102
|
+
neighbors = []
|
|
103
|
+
length = len(grid)
|
|
104
|
+
width = len(grid[0])
|
|
105
|
+
for i in range(max(0, row - distance), min(row + distance + 1, length)):
|
|
106
|
+
for j in range(max(0, col - distance), min(col + distance + 1, width)):
|
|
107
|
+
if i != row or j != col:
|
|
108
|
+
if diagonals or (i == row or j == col):
|
|
109
|
+
neighbors.append(
|
|
110
|
+
(grid[i][j], (i, j))
|
|
111
|
+
) if gimme_indices else neighbors.append(grid[i][j])
|
|
112
|
+
return neighbors
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def get_visible_neighbors(
|
|
116
|
+
grid: List[list],
|
|
117
|
+
row: int,
|
|
118
|
+
col: int,
|
|
119
|
+
distance: int,
|
|
120
|
+
skip_signal: Callable,
|
|
121
|
+
gimme_indices: bool = False,
|
|
122
|
+
) -> List[Any]:
|
|
123
|
+
neighbors = []
|
|
124
|
+
length = len(grid)
|
|
125
|
+
width = len(grid[0])
|
|
126
|
+
for row_dir in range(-distance, distance + 1):
|
|
127
|
+
for col_dir in range(-distance, distance + 1):
|
|
128
|
+
if row_dir != 0 or col_dir != 0:
|
|
129
|
+
current_row = row + row_dir
|
|
130
|
+
current_col = col + col_dir
|
|
131
|
+
while 0 <= current_row < length and 0 <= current_col < width:
|
|
132
|
+
# if grid[current_row][current_col] != skip_signal:
|
|
133
|
+
if not skip_signal(grid[current_row][current_col]):
|
|
134
|
+
neighbors.append(
|
|
135
|
+
(current_row, current_col)
|
|
136
|
+
) if gimme_indices else neighbors.append(
|
|
137
|
+
grid[current_row][current_col]
|
|
138
|
+
)
|
|
139
|
+
break
|
|
140
|
+
current_row += row_dir
|
|
141
|
+
current_col += col_dir
|
|
142
|
+
return neighbors
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def get_manhattan_dist(tuple_a: Tuple[int, int], tuple_b: Tuple[int, int]) -> int:
|
|
146
|
+
return (abs(tuple_b[0] - tuple_a[0])) + abs((tuple_b[1] - tuple_a[1]))
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
authors = ["thetaxfraudguy <57653752+thetaxfraudguy@users.noreply.github.com>"]
|
|
3
|
+
description = "Advent of Code helper library. There are many like it, but this one is mine."
|
|
4
|
+
name = "advoco"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
version = "0.3.0"
|
|
7
|
+
|
|
8
|
+
[tool.poetry.dependencies]
|
|
9
|
+
beautifulsoup4 = "^4.11.1"
|
|
10
|
+
click = "^8.1.3"
|
|
11
|
+
python = "^3.11"
|
|
12
|
+
pytz = "^2022.6"
|
|
13
|
+
requests = "^2.28.1"
|
|
14
|
+
|
|
15
|
+
[tool.poetry.group.dev.dependencies]
|
|
16
|
+
bandit = "^1.7.4"
|
|
17
|
+
mypy = "^0.991"
|
|
18
|
+
types-pytz = "^2022.6.0.1"
|
|
19
|
+
types-requests = "^2.28.11.5"
|
|
20
|
+
pytest = "^7.3.1"
|
|
21
|
+
ruff = "^0.1.7"
|
|
22
|
+
ruff-lsp = "^0.0.45"
|
|
23
|
+
|
|
24
|
+
[tool.poetry.scripts]
|
|
25
|
+
advoco = 'advoco.cli:cli'
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
build-backend = "poetry.core.masonry.api"
|
|
29
|
+
requires = ["poetry-core"]
|