lundi 5 octobre 2020

How to check if an item is not in list and then take action in for loop

In the following code, user enters N pairs of input. if action is r it removes the associated value with r from the list and outputs the median of list after deleting value in a single line. If value associated with r does not exist should print empty! and also if list is empty should print empty! as well. Action a adds value to list and outputs the median of list as well. Assume input list is B= [(a, -3),(a,-2),(r,-3),(a ,2),(a, 10),(r,10),(r,100)].

expected output should be like below:

-3
-2.5
-2
0.0
2
0.0
empty!

But my code prints the last output zero. I am wondering how to add another if statement with condition of if a value is not in the list and wants to remove (r, 100) prints empty!

import statistics
N = int(input())
B = []
for i in range(N):
    b = (input().split())
    action, value = b
    B.append((action, int(value)))
tempList = []
for action, value in B:
    if action == 'a':
        tempList.append(value)

    elif action == 'r':
        try:
            tempList.remove(value)
            
        except ValueError:
            pass
    if len(tempList) == 0:
        print('empty!')
    
    else:
        print(statistics.median(tempList))

Aucun commentaire:

Enregistrer un commentaire