Python : Exit while loop when condition is met - python

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.

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.

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

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

Related

greater than but less than function in python usage

while I was studding python I run into this problem that I'm trying to filter if a number is bigger than n and smaller than x
in other thread I read that you could just do this:
if 10 < a < 20:
whatever
but when I run the code Im getting invalid syntax
while guess != rightnum:
guess=int(input('your guess: '))
diff= abs(guess - rightnum)
if guess > rightnum and diff >= 1000 :
print(random.choice(muchless))
elif guess > rightnum and 1000 > diff >= 100
print(random.choice(less))
elif guess > rightnum and diff < 100
print(random.choice(fewless))
your elif statements don't end with :!
You missed 2 colons
while guess != rightnum:
guess=int(input('your guess: '))
diff= abs(guess - rightnum)
if guess > rightnum and diff >= 1000 :
print(random.choice(muchless))
elif guess > rightnum and 1000 > diff >= 100 :
print(random.choice(less))
elif guess > rightnum and diff < 100 :
print(random.choice(fewless))

Python list index out of range but shouldn't be

startDate, stopDate, startTime, stopTime, startBehavior, and stopBehavior are all lists with the same length. I'm getting a list index out of range in line 5 (if startDate[i] != stopDate[j]) and I'm not sure why. It was working before and now it's not. I'm trying to print the specific behaviors based on the conditions in the if/elif statements.
i = 0
while (i < len(startDate)):
j = 0
while (j < len(stopDate)):
if startDate[i] != stopDate[j]:
j += 1
elif startDate[i] == stopDate[j]:
if stopTime[j] < startTime[i]:
j += 1
elif stopTime[j] > startTime[i]:
if startBehavior[i] != stopBehavior[j]:
j += 1
elif startBehavior[i] == stopBehavior[j]:
print(startBehavior[i])
print(stopBehavior[j])
print('')
i += 1
any help would be appreciated! thank you in advanced!
If you run the following snippet, it will run forever, even though i is clearly greater than 100.
i = 0
while i < 100:
while True:
i += 1
print(i)
Your code is doing something similar -- in the case that i == len(startDate) - 1; startDate[i] == stopDate[j]; stopTime[j] > startTime[i]; and startBehavior[i] == stopBehavior[j], your code will increment i so that i == len(startDate), and then, since j < len(stopDate) is still True, you will not have exited your second while loop. When you try to access startDate[i], you will get an IndexError.
This is somewhat data-dependent so it is possible that it worked before without ever having this issue.

Working with recursion but not with for loop

I have written a code using recursion, but later realized that the depth is too high and does not work for higher level input values. It works completely fine without any issue.
def checkCount(first_window, index=0,reference_list=None):
reference_list = []
count = 0
while index<=len(first_window)-2:
if first_window[index] < first_window[index+1]:
index += 1
count += 1
else: break
if count != 0:
reference_list.append(int((count*(count+1))/2))
count = 0
while index <= len(first_window)-2:
if first_window[index] > first_window[index+1]:
index += 1
count += 1
else: break
if count != 0:
reference_list.append(-int((count*(count+1))/2))
if index > len(first_window)-2: return reference_list
elif first_window[index] == first_window[index+1] and index<len(first_window)-2: index += 1
reference_list = reference_list + checkCount(first_window, index, reference_list)
return reference_list
import random
import time
start = time.clock()
input_array = list(map(int,"188930 194123 201345 154243 154243".split(" ")))
input_array = random.sample(range(1,100),10)
def main():
N = len(input_array)
K = 8
if K == 1: return None
print("Input array: ",input_array)
print("First Window",input_array[:K])
print("Real Output", checkCount(input_array[:K]))
if __name__ == "__main__":main()
Now no matter how I try without recursion, it ends with an infinite loop. I have tried different ways but no progress.
One way I have tried is taking out the recursion statement and returning the referencelist + index:
def checkCount(..):
....
....
return referencelist,index
while index <= K-2:
print("While",index)
reference_list, index = checkCount(new_input, index=0, reference_list=[])
referencelist += reference_list
The application is similar to the here. But we have to deal with tons of data where recursion cannot help. Assume that the input array is greater than 100,000. I am really struck here, I do not understand what logic am I missing. Any help will be grateful.
The first_window variable is only read, and the index variable is only incremented. There is no need for recursion, a simple loop can work.
def check_count(first_window):
reference_list = []
index = 0
while index < len(first_window) - 2:
count = 0
while index <= len(first_window) - 2:
if first_window[index] < first_window[index + 1]:
index += 1
count += 1
else:
break
if count != 0:
reference_list.append(int((count * (count + 1)) / 2))
count = 0
while index <= len(first_window) - 2:
if first_window[index] > first_window[index + 1]:
index += 1
count += 1
else:
break
if count != 0:
reference_list.append(-int((count * (count + 1)) / 2))
if index < len(first_window) - 2 and first_window[index] == first_window[index + 1]:
index += 1
return reference_list
Of course, this algorithm can be optimised, for instance, we can avoid repetitions like: len(first_window) - 2.

taberror-inconsistent use of tabs and space

i'm having problem at (return not alternating).The error is 'inconsistent use of spaces'.Could anyone pls help me.
I tried using proper amount of tabs and spaces but still the problem persists.
def alternating(list):
listDifference = []
if list == []:
return True
alternating = True
lPos = 0
rPos = 1
#appends the difference between values to a new lis
while (lPos < len(list)-1) and (rPos < len(list)):
listDifference.append(list[lPos] - list[rPos])
lPos += 1
rPos += 1
#resets the position
lPos,rPos = 0,1
#checks whether values are alternating or not
while (lPos < len(listDifference)-1) and (rPos < len(listDifference)):
if listDifference[lPos] < 0:
if listDifference[rPos] > 0:
lPos += 1
rPos += 1
else:
return not alternating
elif listDifference[lPos] > 0:
if listDifference[rPos] < 0:
lPos += 1
rPos += 1
else:
return not alternating
return alternating
Your problem is that you are using both tabs and spaces which gives and error, soy you need to use only tabs or only spaces.

Python While Loop Test Scores

I'm trying to create a python program that calculates the average of test scores and terminates when you enter -1. However, I'm having trouble getting it to also ignore test scores that are over 100. I want the program to take say the scores 90, 80, 105, 84, -1 and calculate the average of the 1st, 2nd, and 4th scores skipping the 3rd because it's over 100 and terminating with the-1
Here is what I have:
def main():
sum = 0.0
count = 0
x = input("Enter a number (enter -1 to terminate) >> ")
while x >= 0:
sum = sum + x
count = count + 1
if x>100:
break
x = input("Enter a number (enter -1 to terminate) >> ")
print "\nThe average of the numbers is", sum / count
return
main()
You could add numbers to a list:
nums = []
...
if x <= 100:
nums.append(x)
Then the average is simply:
sum(nums) / float(len(nums))
Your statement if x > 100: break causes the while loop execution to terminate, which isn't what you're looking for. You want it to keep going and ignore the number.
So you could do something like this:
while x >= 0:
if x <= 100:
# Do the calculations
Or, using Python's continue keyword, which automatically starts the next iteration of the parent loop. Like Martjin pointed out, you'd have to add another request in the body of the if statement:
while x >= 0:
if x > 100:
x = input("Enter a number (enter -1 to terminate) >> ")
continue
# Do the calculations
You've already added to the sum and the count by the time you break:
sum = sum + x
count = count + 1
if x>100:
break # too late
Also, break ends the loop. You don't want that. So just avoid the sum and count, but keep looping and inputting:
while x >= 0:
if x <= 100:
sum = sum + x
count = count + 1
x = input("Enter a number (enter -1 to terminate) >> ")
At the point where you test if x>100, you've already incremented the count and added to the sum. The second issue is then what you do on that condition - currently you're jumping out of the while loop, which you want to do if x == -1 but not if x>100!
You could just change break to sum -= x ; count -= 1. But it would be more logical to have only added x to begin with:
while x >= 0:
if x <= 100:
count += 1
sum += x
x = input()
I would probably collect all their entries as such:
entries = list()
while True:
entry = input("Enter a test score (-1 to exit): ")
if entry == -1: break
entries.append(entry)
# we only get here after the user enters -1
entries = [entry for entry in entries if 0 <= entry <= 100]
entries_sum = sum(entries)
entries_average = entries_sum / len(entries)

Categories