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.
v = [0, 5, 5, 0, 6, 6, 0, 7, 7 ]
for i in range(len(v) - 1, -1, -1):
if v[i] == 0 :
v[i] = sum(v[i+1:i+4])
print(v)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…