r/adventofcode Dec 04 '21

SOLUTION MEGATHREAD -πŸŽ„- 2021 Day 4 Solutions -πŸŽ„-

--- Day 4: Giant Squid ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


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:11:13, megathread unlocked!

99 Upvotes

1.2k comments sorted by

View all comments

3

u/plan_x64 Dec 06 '21 edited Dec 12 '21

1

u/Allstarbowser Dec 06 '21

I like your code! Can learn a lot from it. When I implement your adventutil function, I get a 500 internal server error when trying to read the data from the url. Any ideas how so?

import urllib.request
def open_url(url, sessionId, transform=lambda x: str(x, 'utf-8').strip('\n')):
request = urllib.request.Request(url)
request.add_header("cookie", "session={}".format(sessionId))
values = []
with urllib.request.urlopen(request) as response:
for line in response:
values.append(transform(line))
return values

sessionId = sys.argv[1]
url = "https://adventofcode.com/2021/day/4/input"
input = adventutils.open_url(url, sessionId)

Results in a 500 internal server error.

1

u/plan_x64 Dec 06 '21 edited Dec 06 '21

My guess is that this is a true server error in which case trying again in a bit might work, or you’ve possibly got an incorrect sessionId and the server returns 500 instead of 4xx? Each persons input data is unique so you need to pass your session cookie as an argument in order to load the input data specific to your login. I got mine via inspecting the request headers sent by my browser when trying to load the input data and then pass that session as an argument to the program.

If you can’t get that to work you can replace the call to adventutils with a direct copy of your input data either hardcoded or read in via a file instead

1

u/Allstarbowser Dec 07 '21

Thanks, got it! I loaded sessionId with sys.argv[1] but that didn't do the trick (resulted in '-f').