r/adventofcode • u/WeirdFlex9000 • Dec 07 '23
Spoilers [2023 Day 7 (Part 1)] [Python] Ridiculously Short Python Solution
I feel proud, ashamed and disgusted at the same time :D
from collections import Counter
from pathlib import Path
data_raw = Path(__file__).with_name("input.txt").read_text().splitlines()
print(
sum(
(rank0 + 1) * bid
for rank0, (*_, bid) in enumerate(
sorted(
(
max(Counter(hand).values()) - len(set(hand)),
*map("23456789TJQKA".index, hand),
int(str_bid),
)
for hand, str_bid in map(str.split, data_raw)
)
)
)
)
40
Upvotes
7
u/WeirdFlex9000 Dec 07 '23
Found a way to drop the dependency on collections.Counter, which is also even shorter:
5
u/daggerdragon Dec 07 '23
During an active Advent of Code season, solutions belong in the
Solution Megathreads. In the future, post your solutions to the appropriate solution megathread.3
u/WeirdFlex9000 Dec 07 '23
Took me a while, but here's part 2:
2
u/azzal07 Dec 07 '23
The
enumeratetakes a second argument for the start, which could make it a bit nicer especially when you need to parenthesise the addition:Except TypeError: 'ellipsis' object is not iterable...
9
u/georgehotelling Dec 07 '23
This is great, I love the function you came up with for sorting hand ranks! Much simpler than my
if ... elif ... elif...statements!1
u/thygrrr Dec 07 '23 edited Dec 07 '23
What's the advantage of using a set comprehension instead of a list comprehension here?
Regarding the scoring, I like to square the values because strictly
n² > sum(n-1..0)I really love the
"literalstring".indexcallable being passed around. Beautiful. The rest... not so much. (especially the braces)1
u/IronForce_ Dec 08 '23
Can someone explain what is going on in the code? Im having trouble reading it
2
u/Michagogo Dec 07 '23
Impressive. I used Counters too, but just compared different sets of values (first I just added them to the ranked results one at a time, later I built a list of the different types and used .index). One of those things that doesn’t seem like it should work (“wait, what do you mean you’re subtracting the types of cards from the largest set of identical ones? Those are entirely different data types…) but it just happens to line up with the rules.
3
u/LesaMagner Dec 07 '23
People are you able to understand this algorithm by just looking it. I am just wondering if I am little slow. For having to try it out with different inputs and console logging to understand it
0
u/Mats56 Dec 07 '23
This is a good example of why I hate using python at my day job. You have to read it the opposite way of the flow.
`sum (map (for ( sorted (map) for in map)))`
instead of
`map -> sorted -> map -> sum`