if you find yourself struggling don't waste too much time on it, ask here, someone will tell you how to do the python part (while trying to avoid actual spoilers) some of the AOC puzzles will be harder, you want to spend more time on the puzzle and less on the basic stuff.
All in all, AOC should be fun and educational. I learn something new every year.
#AoC 2022 | Day 3 | Solutions & Spoilers
2375 messages · Page 3 of 3 (latest)
will do in future the logic of them haven't been hard so far
just tryna get them done in cleanest way possible
without using 100 if and else statments
how do u read 3 lines at a time
Also, read others answers and then consider rewriting some of your own if you see something you'd like to try.
you can zip it, or chunk it, or just use the index
yeah i wanted to try this one but is this python?
The question now is can github copilot see that you are making an AOC day and give the answer? hmmm.... there are a lot of answer on github in various languages.
Well the format is all the same.
for index in range(0,len(data),3):
a,b,c = data[i:i+3]
or something similar
with open('zzzinp.text','r') as file:
for i in range(3):
lines_3 = [l for l in file][:3*i]
print(lines_3)```
ah, for that method just use readline.
i was writing this but [0:3} never read first item
with open(filename) as file:
for line1 in file:
line2 = file.readline()
line3 = file.readline()
print(line1,line2,line3)
each time we call realine it reads a new line nice
with open('zzzinp.text','r') as file:
lines = file.readlines()
for i in range(0,len(lines), 3):
lines_3 = [l for l in lines][i:3*(i+1)]
clean(lines_3) ```
i did this
that works too. you can also do lines = file.read().splitlines() to read them without the \n
Also, back to the first comment: You really want to avoid using global this way, in fact pretty much you never want to use the global keyword. It's almost always a bad practice, and mostly you only see it with new coders that are still figuring out how to use functions.
if i import this file into another file does the global variable get imported too?
letters = {v: k for k, v in enumerate(string.ascii_letters, 1)}
common_letters = []
total = 0
def clean(first_half):
global common_letters
a, b, c = first_half[0], first_half[1], first_half[2]
common_letters.append(str(set(a).intersection(b).intersection(c)))
with open('zzzinp.text', 'r') as file:
lines = file.read().splitlines()
for i in range(0, len(lines), 3):
lines_3 = [l for l in lines][i:3*(i+1)]
clean(lines_3)
total = 0
for i in common_letters:
total += letters[i.strip("'{}")]
print(total)```
yeah.
but if you're importing it, you'll want to put the inline code into a function so it doesn't get run when you import
maybe that's y my bot was acting weird
how do u remember all the variables
put them into a dict?
I don't remember any variables, I look up the ones I need when I need them.
like ascii_letters. If I couln't remember that, at least I know it exists and I can just check the string page on python docs.
then I import it from the string library.
with open('day3\input.txt', 'r') as f:
inputlist = f.read().split('\n')
total = 0
groupnum = 0
for num in range(int(len(inputlist) / 3)):
position = -1
group = [inputlist[groupnum], inputlist[groupnum + 1], inputlist[groupnum + 2]]
for letter in group[0]:
position += 1
if letter in group[1] and letter in group[2] and letter not in group[0][:position]:
if letter.lower() == letter:
total += (ord(letter.lower()) - 96)
else:
total += (ord(letter.lower()) - 70)
groupnum += 3
print(total)```
Pretty happy with my solution, if anyone has any tips please let me know!
makes sense i'll try to avoide globals
learn about sets. 🙂
for letter in group[0]:
position += 1
if letter in group[1] and letter in group[2] and letter not in group[0][:position]:
vs:
unique = set(group[0]) & set(group[1]) & set(group[2])
Wow, alright will do, anything else that sticks out?
instead of:
group = [inputlist[groupnum], inputlist[groupnum + 1], inputlist[groupnum + 2]]
you could have just extracted 3 values:
g1,g2,g3 = [inputlist[groupnum], inputlist[groupnum + 1], inputlist[groupnum + 2]]
you don't really need the groups to be in a list.
that seems pretty minor though, if you had of done it that way likely someone else would have said "put them in a list".
oh yeah thats true, a list was not necessary
oh, and the big one: range can take 3 parameters.
The reason that works is because of something called a set intersection - sets can only contain unique values, so no duplicates. Getting the intersection of two sets, A & B, gives you another set consisting of any values which are shared between the two sets.
how would that be applicable here?
Damn these puzzles are really well thought out, making you use like every data type throughout the days if you want the most optimal solution
instead of
groupnum = 0
for num in range(int(len(inputlist) / 3)):
groupnum += 3
vs:
for groupnum in range(0, len(inputlist), 3):
this is only day 3. there's still 44 (ish) puzzles left.
Yeah ik but so far the most straightforward/optimal solutions have used lists, dictionaries and sets
Right, I'll have to do some more research into range with multiple parameters
yeah, we'll see a lot of those. expect queues and stacks to be relevant eventually. 🙂
uh oh, I dont even know what they are xD
range( start, stop, step )
ohh, that makes a lot of sense, tysm!
start defaults to 0, and step defaults to 1.
np, yeah that makes sense that should be very helpful for later puzzles
one of the things later puzzles will do is scale part 1 will have a naive solution that will not work for part 2, because part2 will be "now do part 1 another 2 billion times", so you'll need things like sets instead of lists to handle O(1) operations instead of O(n) and things like that
Does the difficulty scale as we get closer to Christmas or is it random?
it's scales up
it hits the peak somewhere between 17-23, and then slows down near the end
weekends are also usually harder
to make everyone feel good by EOY
interesting
it's a bit random: this scatterplot should give you a sense of how difficult each puzzle has been in the past. The points are how long each of the top 100 took to solve that day. like day 8 of last year part 2 was a lot harder than part 1, but day 11 part 2 was easy. day 20 of 2020 was a zinger. as was day 15 of 2018
the scatterplot: https://www.maurits.vdschee.nl/scatterplot/
If you hover over the dots you can see which dot was who and what time they had.
I see, ty
part of the problem is that the puzzle creators and testers think there are obvious answers that the public collectively misses, or vice versa the public find easier answers that the creator and testers missed. so the variance can sometimes be high.
this is compounded by them coming up with so many different input files. there was a path finding problem last year where 1 of the inputs part 2 could be solved like part 1 if you did part1 a certain way, but everyone else's part 2 was much more involved. So even within the puzzles there can be some variance.
Im working on the basis of part two, and I feel like this should get every three keys into their own list, but for some reason i have this [...] item in my list, and I cant figure out anywhere on google if its actually there or what it means?
def part_two():
with open("rucksacks.txt", "r") as f:
data = f.read().split("\n")
group = groups = []
for d in data:
if(((data.index(d) + 1) % 3) == 0):
group.append(d)
groups.append(group)
group.clear()
else:
group.append(d)
['CjhshBJCSrTTsLwqwqwb', 'GtmnFHlDfcpHbLZjtTTRLWwb', 'fDfNHHjVFNvvrvVBJJdS', [...]]
I would rather not get the answer per se, but I have no idea why this is happening
I believe that third list is a really long list, but it's just denoted like that because it's too long
It's probaby because you're setting group and groups to the same list
well i get a group of three elements in group add that to groups and then empty out group for the next three
!e
group = groups = []
group.append(1)
print(group)
print(groups)
@unique pivot :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [1]
002 | [1]
hmm
set them both on different lines
Can someone check over my find_common method? It's supposed to take a list of strings, and find out what letter is common between all of them:
def find_common(self, *args: str) -> str:
for i, text in enumerate(args):
others = args[:i] + args[i+1:]
for j in others:
for letter in text:
if letter in j:
return letter
now i have a list of blank lists lol
this is weird
That would probably be because just appending group appends a reference to the list that group references. When you clear group, it clears all those lists because it's the same ist
oh interesting
I'd suggest just slicing, then appending that
sets :p
:p
ah yikes
even with a common letter
that would explain why my guess is too low
sets sets sets
yes, listen to aboo
ah, lol
Looks like it returns as soon as it finds the first common letter between two of the strings
args[:i] and args[i + 1:] is skipping args[i], isn't it?
oh that's the point.
solved it
def find_common(self, *args: str) -> str:
for i, text in enumerate(args):
others = args[:i] + args[i+1:]
for letter in text:
if all(letter in other for other in others):
return letter
repost if O(n^3)
hmm so just slice like group[-3:] to always get the last three?
since i never reset it
yup came to that same conclusion. thanks!
now to see if i can optimize...
you could do groups.append(data[i:i+3]), and then increment i by 3 repeatedly
or you could do that
are you also building a grouper method?
Why do you need the first for loop?
nope, i can show you what i have now if you are curious it is working though so semi spoiler
I need it to get the index of all other lists. So say I had a list of 3 items, and currently we're on the 2nd item. others would then contain the first and last item
it also contains the text i'm currently looping over
sure
def part_two():
with open("rucksacks.txt", "r") as f:
data = f.read().split("\n")
group = []
groups = []
for d in data:
if(((data.index(d) + 1) % 3) == 0):
group.append(d)
groups.append(group[-3:])
else:
group.append(d)
print(groups)
first half of it
If you're looking for a common letter, that letters going to be in the first string. So you could iterate over the first string then iterate over the rest of them in that comprehension like you already do to check if the first of them have the letter.
Sorry - I'm not quite understanding. It looks like that's what I'm already doing? What about my approach do I need to rethink?
If the letter is common, then that means that any string that you iterate over will have that letter. So instead of iterating over everything, just iterate over the letters of the first one, and check if each letter of it is in the other strings.
Och! Didn't think of that.
def find_common(self, *args: str) -> str:
for letter in args[0]:
if all(letter in other for other in args[1:]):
return letter
That should bring it down to O(n^3)
It works BTW, same solution as before
i don't think it's cubic
what are you trying to do?
or you could just use sets >.>
for letter in args[0]allletter in other for other in args
unless i'm missing something else / misunderstanding time complexity for a certain thing
yeah i used set intersection
he said he wanted to challenge himself :p
ah
boring

Robin have you solved it yet, or are you still working on it?
Solved both, thanks to y'all
in part 2 we are not slicing the words like in part 1 right?
just comparing the entire words to each other?
actually the cool thing about find_common is that I used it in my part one as well
def part_one(self) -> str | int:
total = 0
for backpack in self.backpacks:
c = len(backpack) // 2
compartment_one = backpack[:c]
compartment_two = backpack[c:]
common = self.find_common(compartment_one, compartment_two)
total += self.get_priority(common)
return total
oh it is, but not for the reason you said. the all is linear, but (letter in other for other in args is quadratic. if you always only had 3 strings to compare it would be quadratic, though
dang you actually used a class and everything
fnacy
lol, part of my AoC helper. each day has a placeholder like
from aoc.solution import SolutionABC
class Solution2(SolutionABC):
def __init__(self, content: str) -> None:
...
def part_one(self) -> str | int:
...
def part_two(self) -> str | int:
...
maintainable aoc? never heard of it.
wait who solved in 10s lol
most likely chatgpt
you go in and fill out whatever you want, and run a command
python -m aoc --day 2 --part 1
since they posted on twitter that they used it for day1
all I did was hack together a wonky script for getting the boilerplate out of my way
otherwise its all salt's aoc_lube >.>
i just write the boilerplate at 11:55 🥴
I added a part to mine that runs the solutions for the current day if you don't provide any arguments. Found that useful for making it quicker to type the command.
I'm planning on adding more features like submission for CLI, and test cases
well, I have to create a pdm project, add all my dependencies, the whole thing
I was considering something like that. Do I just use datetime for it?
damn i might get replaced before i can even get a job 😆
hm, I could just have all the solutions be one pdm project and have them share dependencies because I don't care
yeah, that's what I did. Just datetime.now() and get the days and year from it
well, they all use the same dependencies anyways
definitely not, it's wrong in many ways
the idea that ai can replace programmers is something i find absurd, at least right now
😔
Very nice! I'd probably have to remove the year from my config.toml then, lol
year = 2022
session = ""
but it is a great tool to augment the programming experience
Well, it wouldn't work if you tried to run this code a year from now, so...
Hm might be worth keeping it in there then
Each project should be tied to a specific year
i want that c too
well if gpt can solve Aoc what's left
it can solve simple aoc
gpt just did what i spent like 30 minutes doing
it will probably have trouble once problems get harder
I and someone else a while ago plugged in the AoC problems, it got pretty close
that's wrong
look at the last example
it should not give h, world does not include h
it created like 8 blank sets but yeah
i don't think that matters as long as it understands what it needs to do
it has the right idea
lmao dumbass machine
but it cannot necessarily give correct code
I copy+pasted day 3 into chatgpt, lets see what I get
our jobs are safe!
i am also incredibly sad that it does not know what rvsdg is
reduce. THAT was the fuction I was looking for earlier
hahahha so something good did come out of it
plug in part 2. It'll make like 6-8 blank sets and use individual for loops to add stuff to them
i'll just ignore the fact that there's just a single paper on it
it gave me ```py
total_priority = 0
for rucksack in rucksacks:
Split the rucksack into two compartments.
first_compartment = rucksack[:len(rucksack) // 2]
second_compartment = rucksack[len(rucksack) // 2:]
Find the items that appear in both compartments.
common_items = set(first_compartment) & set(second_compartment)
Compute the sum of the priorities of the common items.
compartment_priority = sum(priority(item) for item in common_items)
Add the compartment priority to the total priority.
total_priority += compartment_priority
Print the total priority.
print(total_priority)
for part 1
moment
where priority is ```py
def priority(item):
if item.islower():
return ord(item) - ord('a') + 1
else:
return ord(item) - ord('A') + 27
shit
it's learned
that looks right to me
Interesting, didn't think of using two ords
lets see how it fares with part 2
I just did ```py
priorities = dict(zip(string.ascii_letters, range(1, 53)))
waow that's same as mine 
I was just going to do ord(item) - 64
I had copilot on for the first day and I did the first day a little late, and I didn't even write a comment and it auto completed the rest of the one liner for me
It was a little off, but close
string.ascii_letters.index(x) + 1 >>
index is neater 👀
def get_priority(self, letter: str) -> int:
if letter in ascii_lowercase:
return ascii_lowercase.index(letter) + 1
if letter in ascii_uppercase:
return ascii_uppercase.index(letter) + 1 + 26
That's what I used
thats my solution
i suppose i am ruining all the fun with the code golf lmao
it's not even golf
it gave me ```py
def priority(item):
if item.islower():
return ord(item) - ord('a') + 1
else:
return ord(item) - ord('A') + 27
rucksacks = [
"vJrwpWtwJgWrhcsFMMfFFhFp",
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL",
"PmmdzqPrVvPwwTWBwg",
"wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn",
"ttgJtRGJQctTZtZT",
"CrZsJsPPZsGzwwsLwLmpwMDw"
]
total_priority = 0
Iterate through the rucksacks in groups of three.
for i in range(0, len(rucksacks), 3):
group = rucksacks[i:i+3]
Find the item types that appear in all three rucksacks.
common_items = set.intersection(*(set(rucksack) for rucksack in group))
Compute the sum of the priorities of the common items.
group_priority = sum(priority(item) for item in common_items)
Add the group priority to the total priority.
total_priority += group_priority
Print the total priority.
print(total_priority)
check pins
they've really already had their fun
mans trollin
I have ```py
priorities = dict(zip(string.ascii_letters, range(1, 53)))
def part_1(data: list[str]) -> int:
priorities_sum = sum(
priorities[(set(a) & set(b)).pop()] for a, b in [divide(2, i) for i in data]
)
return priorities_sum
def part_2(data: list[str]) -> int:
priorities_sum = sum(
priorities[(set(a) & set(b) & set(c)).pop()] for a, b, c in chunked(data, 3)
)
return priorities_sum
probably because i did them in like 8 minutes as fast as i could
maybe i should just stop trying
yeah the thing is i'm usually asleep when AoC drops
its unreadable because its not in rust
TRUE
it's 11. are you telling me you have a real sleep schedule??
skill issue
method chaining is a required requirement for readability 😤
mayhaps
I'm usually asleep, and when I wake up I need to go to school
or well, I am awake when AOC drops, but like, I'm busy procrastinating sleep
welp, its probably excessively verbose but i finished my part 2
def part_two():
with open("rucksacks.txt", "r") as f:
data = f.read().split("\n")
group = []
groups = []
for d in data:
if(((data.index(d) + 1) % 3) == 0):
group.append(d)
groups.append(group[-3:])
else:
group.append(d)
commons = []
for group in groups:
commons.append(list(set(group[0])&set(group[1])&set(group[2])))
commons = [ord(char)-96 if char.islower() else ord(char)-38
for common in commons for char in common]
print(f"The sum of the common letters in each group of three is {sum(commons)}")
"come to school"
"no, i'm doing AoC"
aoc:
my gigachad mom genuinely suggested i should skip the first period class at uni if im that invested in aoc lmao
🤨
based mother
"I'm sorry, but I won't be able to attend your educational establishment until the end of december due to important matters, the matter in question being an important and prestigious and importantly important programming advent calendar known as Advent of Code. Its important, BTW."
damn
"pls give me all As so I pass"

you can claim it's for religious purposes
you didnt mention that the event is important
since it's an advent calendar
"care to explain this gap in your resume?"
lol i plan on putting all this on my github
my bad, fixed
thanks
good idea
"If it may please me for your good reputation, you may give me perfect grades to sustain me and my educational attainment in my absence."
"pls no fale"
now i just want to implement caching in my tool because
Oh, hello! Funny seeing you here.
I appreciate your enthusiasm, but you aren't going to find much down here.
There certainly aren't clues to any of the puzzles. The best surprises don't
even appear in the source until you unlock them for real.
Please be careful with automated requests; I'm not a massive company, and I can
only take so much traffic. Please be considerate so that everyone gets to play.
If you're curious about how Advent of Code works, it's running on some custom
Perl code. Other than a few integrations (auth, analytics, social media), I
built the whole thing myself, including the design, animations, prose, and all
of the puzzles.
The puzzles are most of the work; preparing a new calendar and a new set of
puzzles each year takes all of my free time for 4-5 months. A lot of effort
went into building this thing - I hope you're enjoying playing it as much as I
enjoyed making it for you!
If you'd like to hang out, I'm @ericwastl on Twitter.
- Eric Wastl
bri'ish people be like
4-5 months is a really long time, it's amazing how much work he puts into this
he's absolutely based
actually i was thinking about that for day 3
he has to make the inputs in such a way that there's only 1 repeating character
true enough
yeah, it'd be way too tedious to manually write them out
i thought he would given there's a few restrictions here
but writing the puzzles, and the input generation, and everything else is a lot
don't think so
"If that shall not be granted, I may politely send a team of highly trained enforcers to each of your addresses: <REDACTED ADDRESS 1>, <REDACTED ADDRESS 2>, etc. I expect that you shall take this not-a-threat seriously."
i mean i know you can probably just get the answers that way but for folks who don't mind being spoiled and want to help
playing me huh
What does this guy doing for a living?
make advent of code puzzles probably
I have a puzzle idea! Can I send it to you?
Please don't. Because of legal issues like copyright and attribution, I don't accept puzzle ideas, and I won't even read your email if it looks like one just in case I use parts of it by accident.
— https://adventofcode.com/2022/about
his twitter says he works at TCGplayer https://twitter.com/ericwastl
could probably fix that by slapping an appropriate license or something
i actually emailed the guy today
he got back to me really fast
lol
lol about what
my goofy ass after uploading my session token to github
env vars my beloved
how hard does he work on the puzzles to even have free time to respond to issues like this
i'm guessing he's probably in that grace period when an AoC starts
it's still time consuming managing the ongoing one but I suppose maybe not as much as actually making them
regardless the guy is the most based gigachad i've ever seen

git rebase -i {COMMITISH}
...
git push --force
the thing is
that won't remove it from the history if someone has the hash
mine is set up as a "github template"
so when i make changes to the template repository i have to delete my actual 2022 aoc solutions
like delete the whole repo, make a new one, and clone it
yeah
Can someone help me understand why I can't append item to badge (at the very bottom)?
for sack in data:
counter += 1
commonItemTypes.append(sack)
if counter == 3:
counter = 0
commonItemTypesOne, commonItemTypesTwo, commonItemTypesThree = commonItemTypes[0], commonItemTypes[1], commonItemTypes[2]
commonItemTypes = []
print(commonItemTypesOne, commonItemTypesTwo, commonItemTypesThree)
for item in commonItemTypesOne:
if item in commonItemTypesTwo and item in commonItemTypesThree:
badge.append[item]
I defined badge as an empty list earlier
Ah, you're right
Sorry, that's a really silly mistake
Well, after that quick fix, here's my solution to day 3 part 2
with open('input.txt', 'r') as file:
data = file.read().split()
def listToPriority(itemTypes):
priorityList = []
for letter in itemTypes:
if letter.isupper():
priorityList.append((ord(letter) - 38))
else:
priorityList.append((ord(letter) - 96))
return sum(priorityList)
commonItemTypes = []
badge = []
counter = 0
for sack in data:
counter += 1
commonItemTypes.append(sack)
if counter == 3:
counter = 0
commonItemTypesOne, commonItemTypesTwo, commonItemTypesThree = commonItemTypes[0], commonItemTypes[1], commonItemTypes[2]
commonItemTypes = []
for item in commonItemTypesOne:
if item in commonItemTypesTwo and item in commonItemTypesThree:
badge.append(item)
break
badgeSum = listToPriority(badge)
print(badgeSum)
An AI. it was fed into google's AI and it soved part 1 in 10 seconds.
Had to catch up for the last three days but I found a good use for that walrus operator in this one
from itertools import islice
from string import ascii_letters
import typer
# Answer 2545
def main(filename: typer.FileText = typer.Argument(...)):
priority = 0
while group := list(islice(filename, 3)):
priority += (
ascii_letters.index(
list(
set(group[0].strip())
& set(group[1].strip())
& set(group[2].strip())
)[0]
)
+ 1
)
print(priority)
if __name__ == "__main__":
typer.run(main)
This is the day 3 channel, please don’t post spoilers for day 4 in here
hello @radiant zealot, I've deleted your message
you could perhaps post your message in #1048826930759204864 and link it here (with a disclaimer) if you wish to do so
Ah ok sorry about that
Day 3 puzzle kinda gave me a bit of a struggle writing unit tests giving false positives. Need more practice writing proper test cases. Solution spoiler link here: https://github.com/Qoyyuum/adventofcode/tree/main/2022/day03
you can consider bringing in sets to your solution, it'll make it more concise
more specifically, doing a set intersection
woohoo ⭐```py
ELF_CHUNKS = 3
LOWER_OFFSET = 96
UPPER_OFFSET = 38
def calculate_priority(item):
return ord(item) - (LOWER_OFFSET if item.islower() else UPPER_OFFSET)
with open("./input.txt") as file:
raw = file.read().splitlines()
input = [raw[i:i+ELF_CHUNKS] for i in range(0, len(raw), ELF_CHUNKS)]
priorities = []
for chunk in input:
unique_chunk = [set(rucksack) for rucksack in chunk]
for item in set("".join(chunk)):
if all(item in rucksack for rucksack in unique_chunk):
priorities.append(calculate_priority(item))
print(sum(priorities))
wait a minute 👀
i forgot about & lmfao
BRUHHHHHHHHHHHHHHHH
Good idea. I'll see if I can get around to it but in the meantime, I'll just put it as a Github issue.
# aoc problem 3
lowercase_priorities = {chr(i + 0x60): i for i in range(1, 27)}
uppercase_priorities = {chr(i + 0x40): i + 26 for i in range(1, 27)}
priorities = lowercase_priorities | uppercase_priorities
def getinput():
with open('3.txt') as f:
return f.read().splitlines()
def splithalves(inpt):
acc = []
for line in inpt:
hlen = len(line) // 2
acc.append((line[:hlen], line[hlen:]))
return acc
def dup_item_priority(lh, rh):
dup_item ,= set(lh) & set(rh)
return priorities[dup_item]
def groupthree(inpt):
return [inpt[i:i+3] for i in range(0, len(inpt) // 3, 3)]
def common_item_priority(r0, r1, r2):
common_item ,= set(r0) & set(r1) & set(r2)
return priorities[common_item]
def main():
inpt = getinput()
print(sum(dup_item_priority(lh, rh) for lh, rh in splithalves(inpt))) # solution part 1
print(sum(common_item_priority(r0, r1, r2) for r0, r1, r2 in groupthree(inpt))) # solution part 2
if __name__ == '__main__':
main()
```why is my part 2 solution wrong?
help pls
You're cutting the grouping. Let's say we have 12 lines.
You do range(0, 12//3, 3)
Which will only give you 0 and 3.
You want the range to go the full len(input). Not //3
o thanks
what do you mean not all of them???
import string
with open("python_sandbox/RevivalOfCode/2022/Day3/data.txt", "r") as rucksack:
rucksack = rucksack.read().split("\n")
sum = 0
alphabeth = {letter : ord(letter) - (96 if letter.islower() else 38) for letter in string.ascii_letters} #Makes a dictionary of the { keys(alphabeth):values(numbers) } for lower and uppercase letters
for compartments in rucksack:
for j in compartments[0:int(len(compartments)/2)]: # FIRST COMPARTMENT (Gets first half of the string)
for k in compartments[(int(len(compartments)/2))+1 :]: #SECOND COMPARTMENT (Gets last half of the string)
if j in k:
sum+= alphabeth[j]
print(sum)```
bruh... this doesnt work... idk why tho
says that my answer is too high
have you tried testing against the test input instead?
maybe that will help you figure out what's wrong
ive just ried.. it seems fine
lemme show you
i tested it on the first 2 strings using for compartments in rucksack[:2]
which is
BzRmmzZHzVBzgVQmZLPtqqffPqWqJmPLlL
hpvvTDcrCjhpcrvcGGhfLHMlLtMCqflNlWPJlJ
you tested it on your actual input?
the first 2 string in it
that's not what I'm referring to
there's an example input in the problem description itself
oh... i should try that
you have 6 example rucksacks and the priority numbers for each
they are literally given so that you can test your code against them :)
oh
thanks
@quiet heath i figured out the problem...
Ah, what was it?
lets say the string is LLqwLL
youd want the value of L 38
what my programm was doing was getting the value for each identical letter in the halves
so id get 76
@quiet heath
class set([iterable])``````py
class frozenset([iterable])```
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be [hashable](https://docs.python.org/3/glossary.html#term-hashable). To represent sets of sets, the inner sets must be [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset "frozenset") objects. If *iterable* is not specified, a new empty set is returned.
Sets can be created by several means:
• Use a comma-separated list of elements within braces: `{'jack', 'sjoerd'}`
• Use a set comprehension: `{c for c in 'abracadabra' if c not in 'abc'}`
• Use the type constructor: `set()`, `set('foobar')`, `set(['a', 'b', 'foo'])`...
Similar names: label.set
imma have to research it more.. im new to python.. it might be evident
ive never used sets before.. i just wirk on personal projects
Sets are definitely useful
They are part of the core Python language for a reason :)
haha .. yeeah , i would guess
u are very friendly .. is it ok if i add you?
Eh, I prefer to chat on the server if that’s ok
i get you haha
hey tom
i did wha u told me and i still have issues
import string
with open("python_sandbox/RevivalOfCode/2022/Day3/data.txt", "r") as rucksack:
rucksack = rucksack.read().split("\n")
sum = 0
alphabeth = {letter : ord(letter) - (96 if letter.islower() else 38) for letter in string.ascii_letters} #Makes a dictionary of the { keys(alphabeth):values(numbers) } for lower and uppercase letters
for compartments in rucksack:
for j in set(compartments[:int(len(compartments)//2)]): # FIRST COMPARTMENT (Gets first half of the string)
for k in set(compartments[int(len(compartments)//2)+1 :]): #SECOND COMPARTMENT (Gets last half of the string)
if j in k:
sum+= alphabeth[j]
print(sum)```
when i test the example the answer given is correct
but when i test the data they gave is it says that the number i got is too low.
#Advent of code
#Problem 2
#--- Day 3: Rucksack Reorganization ---
import string
with open("day3inp.txt") as f:
inp = f.read()
li1 = [list(map(str, i.split("\n"))) for i in inp.strip().split("\n\n")]
alphabet_string = string.ascii_letters
#PART 1
letter_sum = 0
for i in li1[0]:
half_length_item = len(i)//2
first_half = i[:half_length_item]
second_half = i[half_length_item:]
common_item = ''.join(set(first_half).intersection(second_half))
#find out the common letter between them
letter_sum += (alphabet_string.index(common_item)+1)
print(letter_sum)
#PART 2
total_common_itemType_sum = 0
for i in range(len(li1[0])):
if i%3==0:
elf_group = li1[0][i:i+3]
common_item_2 = ''.join(set(elf_group[0]).intersection(elf_group[1]))
common_item_3 = ''.join(set(common_item_2).intersection(elf_group[2]))
total_common_itemType_sum += (alphabet_string.index(common_item_3)+1)
else:
pass
print(total_common_itemType_sum)
hehe 🙂
set 😎
i am happy that i got it on my first try and it also took so little time
Hey @dire garden!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
oh damn
what do you think about my way for p1?
# Rucksack Reorganization
# https://adventofcode.com/2022/day/3
import string
def calculate_item_priority(item: str):
if len(item) != 1:
raise ValueError("item must be a one-character-long string")
if item not in string.ascii_letters:
raise ValueError("item must be a letter")
return string.ascii_letters.index(item) + 1
total_points = 0
input_ = open("Day 3/input.txt", "r")
for line, content in enumerate(input_, 1):
content = content.removesuffix("\n")
firstpart, secondpart = (
content[: int(len(content) / 2)],
content[int(len(content) / 2) :],
)
common_item = list(set(firstpart).intersection(set(secondpart)))[0]
common_item_priority = calculate_item_priority(common_item)
total_points += common_item_priority
print(total_points)