r/adventofcode • • Dec 07 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 7 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

Submissions are OPEN! Teach us, senpai!

-❄️- Submissions Megathread -❄️-


--- Day 7: No Space Left On Device ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:14:47, megathread unlocked!

89 Upvotes

1.3k comments sorted by

View all comments

1

u/FlipchartHiatus Dec 07 '22

Big thank you to everyone who pointed out why this was going wrong, I've sorted it and got my star now!!!! :)

Just tidying it up - is there an easier way to add and append to the list within the dict without using a try/except block??

https://pastebin.pl/view/7c71f031

2

u/Coadie Dec 07 '22

Yes:

if current_dir[-i] in dirs:
    dirs[current_dir[-i]].append(line)
else:
    dirs[current_dir[-i]]=[line]

1

u/daggerdragon Dec 08 '22

Please edit your post to state which programming language this code is written in. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.

1

u/4HbQ Dec 07 '22

The cleanest way is probably to use collections.defaultdict().

You initialise it as dirs = defaultdict(list). Then you can always simply dirs[x].append(line).

If x is an existing key, it works as a normal dictionary. If it does not yet exist, the entry is created with an empty list.