Ask Your Question

# Can a loop be made to skip an iteration if the run time exceeds a certain amount?

I apologize if this is a little abstract, but is it possible to create some sort of "for" or "while" loop that will pass to the next iterate if the computation for that specific iterate takes too long?
For example, it could be something along the lines of, for some function/procedure

F(n)


we have

for n in range(100):
print(F(n))


but if for some n in the range, the computation of F(n) takes more than say, 1 minute CPU time, I want it to either just skip to computing F(n+1) and/or print "-1" in place of F(n).
So let's say F(0), F(1), and F(2) all take less than half a second to compute they print just fine, so then n gets set to n=3, and F(3) starts running, but let's say it runs for over a minute, I want it to be that the loop outputs "-1" (or something) and then moves on to computing F(4).

UPDATE: I'd also like to be able, if possible, to print out run times. So that the output would be something like

(F(1), time(1))
(F(2), time(2))
(F(3), times(3))
...


etc., where time(n) is the amount of time it took to compute F(n).

edit retag close merge delete

## 1 Answer

Sort by » oldest newest most voted

Something like this

            try:
alarm(3)
33**33
except AlarmInterrupt:
print("This takes too long.")
continue

more

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

Asked: 2020-06-10 06:36:45 +0100

Seen: 204 times

Last updated: Jun 10 '20