Reputation: 376
I solved Project Euler's Problem 67 a few months back with a wildly inefficient algorithm. Today, I realized how this could have been done better, and while trying to make a more efficient algorithm, I ran into some problems.
The code is this:
r_prev = [59,0,0]
r_load = [73,41,0]
r = [0,0,0]
zero_r = [0,0,0]
rows = 3
while rows != 0:
position = 0
for x in r_load:
try:
if r_prev[position] > r_prev[position-1]:
r[position] = r_prev[position] + r_load[position]
else:
r[position] = r_prev[position-1] + r_load[position]
except IndexError:
r[position] = r_prev[position] + r_load[position]
position += 1
print r
rows -= 1
r_load = input("Enter next row")
r_prev = r
r_prev.append(0)
zero_r.append(0)
r = zero_r
It works by keeping only the sum of the highest path to get to a point. I am feeding it input manually at this point (via the console). When fed the first line, it performs as expect, but when fed the second line, it considers r_prev
and r
as the same thing, and every operation that is performed on r_prev
is also performed on r
.
How do I solve this problem?
Upvotes: 0
Views: 70
Reputation: 251355
When you do r_prev = r
you are not copying the list. You are giving the same list an additional name. To make a copy, do r_prev = list(r)
.
Upvotes: 4