I have to start looping a vector from its end to zero. When I meet the value 0 I need to replace it with the sum of the three previews values. The exception will be for the first zero met, I need just to sum the previous two values.
e.g.
JavaScript
x
2
1
v = [0, 5, 5, 0, 6, 6, 0, 7, 7 ]
2
Expected result:
JavaScript
1
2
1
v = [36, 5, 5, 26, 6, 6, 14, 7, 7 ]
2
Code
JavaScript
1
4
1
for i in range(len(v), 0):
2
if v == 0 :
3
v[i] = v[i+1] + v[i+2] + v[i+3]
4
The code is not working. Where am I wrong?
Advertisement
Answer
You can avoid index errors with sum(v[i+1:i+4])
. You have to compare each element (if v[i] == 0
) not the whole list.
JavaScript
1
7
1
v = [0, 5, 5, 0, 6, 6, 0, 7, 7 ]
2
3
for i in range(len(v) - 1, -1, -1):
4
if v[i] == 0 :
5
v[i] = sum(v[i+1:i+4])
6
print(v)
7