2

Im trying to iterate over my list and calculate the diff between each element and the element following it. If the difference is greater than 0 ( or positive ) then increment up and decrease down by 1 ( if it is greater than 0 ). Similarly if difference is less than 0 then increment down and decrease up by 1 ( if greater than 0 ) . I want to exit out of the loop if either the up or down exceeds limit which is set to 3.

My code:

my_list = [13.04, 12.46, 13.1, 13.43, 13.76, 13.23, 12.15, 12.0, 11.55, 14.63]

up = 0
down = 0
limit = 3

while (up < limit) or (down < limit) :
    for i in range(len(my_list)-1):
        diff = my_list[i] - my_list[i+1]
        print (diff)
        if diff > 0:
            up +=1
            if down > 0:
                down -=1
        elif diff < 0:
            down +=1
            if up > 0:
                up -=1

Obviously this is not working since I keep getting caught up in an infinite loop and cant figure out what I am doing wrong.

0

3 Answers 3

3

The while condition is wrong. The loop keeps going while either up or down is below limit, so it will not stop even when up=1000, as long as down<3. What you want is while (up < limit) and (down < limit) instead.

Sign up to request clarification or add additional context in comments.

Comments

1

do not use while , you can use if condition in last of for loop for break it :

for i in range(len(my_list)-1):
    diff = my_list[i] - my_list[i+1]
    #print (diff)
    if diff > 0:
        up +=1
        if down > 0:
            down -=1
    elif diff < 0:
        down +=1
        if up > 0:
            up -=1
    if (up > limit)or (down > limit) :print(up);print(down);break

1 Comment

While the main issue was changing and to or , this one makes sense too
0

The problem is with your condition. You said you want to exit the program if either the up or down exceeds the limit which is set to 3. So the condition on the while loop needs to be set as while up is less than limit AND down is also less than limit, only then execute the body of the loop. Something like this.

while up < limit and down < limit:

or you can also use brackets (doesn't matter in this case)

while (up < limit) and (down < limit):

So the full program will be

my_list = [13.04, 12.46, 13.1, 13.43, 13.76, 13.23, 12.15, 12.0, 11.55, 14.63]

up = 0
down = 0
limit = 3

while up < limit and down < limit:
    for i in range(len(my_list)-1):
        diff = my_list[i] - my_list[i+1]
        print (diff)
        if diff > 0:
            up +=1
            if down > 0:
                down -=1
        elif diff < 0:
            down +=1
            if up > 0:
                up -=1

Comments

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.