Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import traceback
- import math
- def leggi_voti(filename):
- """
- return a tuple (int, int, bool) from file
- format must be (parsable_int) (parsable_int or string) (Optional boolean)
- """
- voti = []
- with open(filename, 'r') as f:
- for line in f:
- tokens = line.strip().split()
- matricola = int(tokens[0])
- voto = int(tokens[1]) if tokens[1].isdigit() and int(tokens[1]) >= 18 else -1 # means not sufficient !USE SAME TYPE
- lode = True if len(tokens) > 2 and bool(tokens[2]) == True else False
- voti.append((matricola, voto, lode))
- return voti
- def only_sufficienti (lista_voti):
- """
- restituisce una lista di persone sufficienti:
- es:
- >>> only_sufficienti([(1, 18, False), (2, 30, True), (3, 15, False)])
- [(1, 18, False), (2, 30, True)]
- """
- return [x for x in lista_voti if x[1] > 0]
- def media_sufficienti(lista_voti):
- '''Deve restituire il voto medio considerando solo
- gli studenti che hanno ottenuto un punteggio sufficiente
- '''
- # L = []
- # n = 0
- # votox = True
- # for i in range(len(lista_voti)): #NO!!!!!
- # if lista_voti[i][1] != 'ins':
- # votox == False
- # if votox == True:
- # L.append(lista_voti[i][1])
- # n += 1
- # media =(sum(L))/n
- # return media
- sufficienti = only_sufficienti(lista_voti) # filter only interested items
- return sum([x[1] for x in sufficienti]) / len(sufficienti) # sum / count
- def media_e_std_sufficienti(lista_voti):
- '''Deve restituire il voto medio e la deviazione standard dalla media
- considerando solo gli studenti che hanno ottenuto un punteggio
- sufficienti pastepin
- '''
- # L = []
- # n = 0
- # votox = True
- # for i in range(len(lista_voti)): # NO!!!!!
- # if type(lista_voti[i][1]) == int: # use isinstance, ALSO USE THE SAME TYPE
- # votox == False # ??? (facepalm)
- # if votox == True:
- # L.append(lista_voti[i][1])
- # n += 1
- # media =(sum(L))/n
- # from math import sqrt
- # std = 0
- # for i in range(n):
- # std += (L[i]-media)**2
- # std = sqrt(std/n)
- # return std,media
- sufficienti = only_sufficienti(lista_voti)
- media = media_sufficienti(sufficienti)
- deviazione = sum([(x[1] - media) ** 2 for x in sufficienti]) / len(sufficienti)
- return media, deviazione
- if __name__ == '__main__':
- filename = 'voti_studenti.txt'
- try:
- voti = leggi_voti(filename)
- sufficienti = media_sufficienti(voti)
- print('sufficienti:', sufficienti)
- std_sufficienti = media_e_std_sufficienti(voti)
- print('std sufficienti:', std_sufficienti)
- except FileNotFoundError as e:
- print(f'file {filename} does not exists')
- except Exception as e:
- traceback.print_exc()
- print(e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement