0

I guess this should be simple. The first part of the code is to initialize the variables. My problem is with the while loop. If the condition j == len(time) is achieved, I need to exit the WHILE loop and the FOR loop. But the thing is that once the condition is true, the while loop iterates once again; therefore, time is out of index.

import numpy as np

# Variables to initialize the problem
timeframe = 25
dt=0.025
dat=[(0, 5)]
dat.append((timeframe,dat[len(dat)-1][-1]))
time = np.arange(dat[0][0],dat[-1][0]+dt,dt)   
dat_discretized = np.zeros(len(time)) 

#While inside a for loop
j=0
for i in range(len(dat)):
    while   dat[i][0] <= time[j] <= dat[i+1][0]:
       dat_discretized[j] = dat[i][1] 
       j += 1
       print(j)
       if j == len(time):
           break

How can I exist the while loop without rechecking the while condition?

2
  • I'm pretty sure you don't even need these two loops, it can be accomplished with numpy indexing. Can you describe what you're trying to do? Commented Dec 27, 2021 at 20:45
  • Once you fix this, you'll find dat[i+1][0] also errors out, since you might be calling dat[len(data)]. You need to define the border case by either doing for i in range(len(dat)-1): or defining the last case explicitly. Commented Dec 27, 2021 at 20:46

1 Answer 1

3
for i in range(len(dat)):
    breakFor=false
    while   dat[i][0] <= time[j] <= dat[i+1][0]:
       dat_discretized[j] = dat[i][1] 
       j += 1
       print(j)
       if j == len(time):
           breakFor=true
           break
    if breakFor:
        break
Sign up to request clarification or add additional context in comments.

1 Comment

The booleas False/True should be in capital letters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.