AdventofCode day 1 part 2, question.
Hello,
I recently started AdventOfCode as a newbie to python in hope to learn some useful skills and just improve overall.
Just some background info - Advent of python gives you a list of numbers preceded by a '+' or '-', then starting from 0, you must iterate through the list.
The first part of the challenge was to find the total sum of all the values they give you which was not an issue.
But in the second part, I ran into a couple of problems.
The second part asks you to find the first repeating sum, if you reach the end to reiterate through until you find a total sum that has occurred before.
e.g : +1, -2, +1 should have an output of 0.
+3, +3, -2, +3, +2, -6 should have an output of 3.
+7, +7, -2, -7, -4 should have an output of 14.
Anyway at first I tried this code:
import itertools
values = [approx 994 values]
total = 0
seen = [0]
for e in itertools.cycle(values):
total += e
if total in seen:
print(total)
break
else:
seen.append(total)
But this never seemed to return any values, and would just go on and lag until I stopped the code from running myself.
Then I made a couple changes:
import itertools
values = [+1, -1......]
total = 0
seen = {total}
for e in itertools.cycle(values):
total += e
if total in seen:
print(total)
break
else:
seen.add(total)
This on the other hand worked, and returned a value immediately.
My question/confusion is why the second code worked but the first didn't.
If someone could please explain this that would be much appreciated!
edit: formatting issues.
Posted Dec 6, 2018, 1:33 AM UTC · edited