2

if in a for loop, I have a variable, it doesn't change for 30 times, I will stop the loop.

for i in range(100):
    if b > a:
      c= 0
    if b < a:
      c = 1

If c stays at 0 continually for more than 30 times,then I will stop it. How to write code for this part?

I am thinking using list to record them, if sum(i for i in c[-30:]) is 0.

Is there any other decent way to express this? Thank you~

1
  • keep a count, break if count > 30? Commented Nov 3, 2017 at 22:08

2 Answers 2

2

Simple thing to do will be, to put another if statement inside the loop

j = 0
for i in range(100):
  if b > a:
    c= 0
    j+=1
  if b < a:
    c = 1
    j = 0
  if j>=30:
    break
Sign up to request clarification or add additional context in comments.

4 Comments

ops, I removed my comment sorry- I didn't think you'd reply, it was "j++ isn't valid syntax" just for future's sake.
how to show it is continually 0, like it could be 0,0,0,1,0, if I asked when exceed 4. I need it to stop when it does not change anymore, it is 1,0,1,0,0,0,0. Like this.
@XiaoyuHan that is why there is j=0 after c=1. This will make the continuous counter 'j' 0 after it changes from that value.
I see...Thank you!!
1

Something like this?

misses=0
THRESHOLD = 30
for i in range(100):
    if b > a:
        misses += 1
        if misses >= THRESHOLD:
             break
        c= 0
    if b < a:
        misses = 0
        c = 1

4 Comments

How to stop when I need all the 0 stays together. I mean c is always the same, and the value of c is 0 for more than 30 times.
misses is increased from 0 to THRESHOLD for each successive c=0 you have (note that what really matters is that b > a). As soon as misses reach 30, you break out of the loop.
Also, note that misses gets reset to 0 if b < a, so that you're effectively counting only the successive occurrences of b > a.
Got u! Thank you~~

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.