Reputation: 483
I have some code intended to update the value of 'time' for each of 5 elements. However, when the value reaches 15, the value after it is not counted. This is the code:
def get_new_theta(msg, theta, time):
new_theta = [theta]
new_time = [time]
for a, b in zip(msg[3::5], msg[4::5]):
new_theta.append(new_theta[-1] + a + b)
new_time.append(new_time[-1]+time)
return new_theta[:-1], new_time[:-1]
msg = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
theta = 1
time = 4.5
for i, (theta, time) in enumerate( zip(*get_new_theta(msg, theta, time)) ):
for j in range(5):
print(theta, msg[i*5+j], time)
The output should be like this:
1 1 4.5
1 2 4.5
1 3 4.5
1 4 4.5
1 5 4.5
10 6 9.0
10 7 9.0
10 8 9.0
10 9 9.0
10 10 9.0
29 11 13.5
29 12 13.5
29 13 13.5
29 14 13.5
29 15 13.5
58 16 18 <-- the values after 15 do not print
58 17 18
Need help from this forum. Thank you.
Upvotes: 2
Views: 72
Reputation: 7141
The problem is that your loops don't go quite that far. Note that new_theta
has 4 values in it, and you return 3 of those. Your outer loop for i, (theta, time) ...
executes 3 times, the inner loop for j in range(5)...
executes 5 times for each of those 3 times for a total of 15 iterations. That's why the last number printed is 15.
In this case, the fix isn't really obvious and depends on what you want to do. The following at least gets through all 18 values without error by modifying the outer loop to run 4 times and modifying the inner loop to exit at the 19th run (since you don't have a full 5 messages to iterate through).
def get_new_theta(msg, theta, time):
new_theta = [theta]
new_time = [time]
for a, b in zip(msg[3::5], msg[4::5]):
new_theta.append(new_theta[-1] + a + b)
new_time.append(new_time[-1]+time)
return new_theta, new_time
msg = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
theta = 1
time = 4.5
for i, (theta, time) in enumerate( zip(*get_new_theta(msg, theta, time)) ):
for j in range(5):
if i*5+j >= len(msg):
break
print(theta, msg[i*5+j], time)
Upvotes: 3