#!/usr/bin/python -tt #======= #Crediti #======= # esercizi corso di python @ifac-cnr # Copyright 2012 Nicola ZOppetti # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 #==================== #Indicazioni generali #==================== # RIEMPIRE LE FUNZIONI # DOVE COMPARE IL COMMENTO # ##-METTI-QUI-IL-TUO-CODICE-## # Seguire le istruzioni riportate nel commento # precedente ciascuna funzione da riempire # Una volta studiata una soluzione ad un esercizio, # per verificare se è corretta eseguire QUESTO SCRIPT # # Per un generico 'esercizio 1', se la soluzione è errata o non data # sullo standard output viene stampato il prefisso KO, il valore restituito e quello atteso # >>> esercizio 1 # >>> KO restituisce: None, risultato atteso: [98, 55, 10, 8, 2] # # Se la soluzione è corretta: # sullo standard output viene stampato OK # >>> esercizio 1 # >>> OK #=============== #INIZIO ESERCIZI #=============== import numpy as np # ----------------- # creaarray2D(n) # ----------------- # # crea l'array con # ndim = 2 # shape = (n,n) # tipo intero di 2 byte # ed il contenuto derivato dagli esempi sotto # # Esempi: # >>>creaarray2D(3) # [[ 0. 1. 2.] # [ 10. 11. 12.] # [ 20. 21. 22.]] # # >>>creaarray2D(6) # [[ 0, 1, 2, 3, 4, 5], # [10, 11, 12, 13, 14, 15], # [20, 21, 22, 23, 24, 25], # [30, 31, 32, 33, 34, 35], # [40, 41, 42, 43, 44, 45], # [50, 51, 52, 53, 54, 55] , dtype = ] def creaarray2D(n): ##-METTI-QUI-IL-TUO-CODICE-## return def creaarray2D(n): ##-METTI-QUI-IL-TUO-CODICE-## return #(2) # ----------------- # creaarray3D(n) # ----------------- # # crea l'array con # ndim = 3 # shape = (n,n,n) # Esempi: # >>>creaarray3D(3) # [[[ 0. 1. 2.] # [ 10. 11. 12.] # [ 20. 21. 22.]] # # [[ 100. 101. 102.] # [ 110. 111. 112.] # [ 120. 121. 122.]] # # [[ 200. 201. 202.] # [ 210. 211. 212.] # [ 220. 221. 222.]] # ] def creaarray3D(n): ##-METTI-QUI-IL-TUO-CODICE-## return #--------------------- #def mezzaemezza(n,m): #--------------------- # restituisce l'array (n x 2m) # composto da m colonne di zeri ed m colonne di uni (interi) # #Esempi: ##>>> mezzaemezza(2,3) ##array([[0, 0, 0, 1, 1, 1], ## [0, 0, 0, 1, 1, 1]]) # ##>>> mezzaemezza(4,2) ##array([[0, 0, 1, 1], ## [0, 0, 1, 1], ## [0, 0, 1, 1], ## [0, 0, 1, 1]]) def mezzaemezza(n,m): ##-METTI-QUI-IL-TUO-CODICE-## return # -------------------------------- # estrai_colonna_2Darray(arr,icol) # -------------------------------- # estrae la colonna con indice icol dall'array bidimensionale arr # e la restituisce come array monodimensionale # esempio # >>> a = array([[ 0, 1, 2, 3, 4], # [ 5, 6, 7, 8, 9], # [10, 11, 12, 13, 14], # [15, 16, 17, 18, 19], # [20, 21, 22, 23, 24]]) # >>> estrai_colonna_2Darray(a,2)) # [ 2 7 12 17 22] def estrai_colonna_2Darray(arr,icol): ##-METTI-QUI-IL-TUO-CODICE-## return # -------------------------------- # estrai_colonna_2Darray_2(arr,icol) # -------------------------------- # estrae la colonna con indice icol dall'array bidimensionale arr # e la restituisce come array bidimensionale che ha una colonna e # tante righe quante le righe dell'array originario # esempio # >>> a = array([[ 0, 1, 2, 3, 4], # [ 5, 6, 7, 8, 9], # [10, 11, 12, 13, 14], # [15, 16, 17, 18, 19], # [20, 21, 22, 23, 24]]) # >>> estrai_colonna_2Darray_2(a,2)) # [ [2] # [7] # [12] # [17] # [22]] def estrai_colonna_2Darray_2(arr,icol): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------------- # load_file_base(pathfile) #------------------------- # caricare il contenuto del file '12_structarr.txt' # in un array strutturato sapendo che: # - le righe che iniziano con % sono commenti # - il file contiene 4 colonne dati separate da spazi o tab # con i seguenti nome,tipo # -- rango - intero # -- lemma - stringa (massimo 10 caratteri) # -- frequenza - intero # -- dispersione - float # # restituire un oggetto np.array strutturato (dati nell'esempio) tale che # a ciascuna colonna sia associato un array monodimensionale che può essere 'estratto' da 'dati' # con il relativo nome: # Esempio: # >>> dati = load_file_base('12_structarr.txt') # >>> dati['rango'] # [21 42 49 7 63 14 35 56 28] # >>> dati['lemma'] # np.array([b'they' b'her' b'as' b'to' b'take' b'you' b'go' b'think' b'not'], dtype='S10') # >>> dati['frequenza'] # [1865844 969591 829018 6332195 670745 3085642 1151045 772787 1638883] # >>> dati['dispersione'] # [ 0.96 0.91 0.95 0.98 0.97 0.92 0.93 0.91 0.98] def load_file_base(pathfile='12_structarr.txt'): ##-METTI-QUI-IL-TUO-CODICE-## return #http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html #------------------------- # load_file_adv(pathfile) #------------------------- # caricare il contenuto di un generico file # in un array strutturato sapendo che: # - le prime due righe (che iniziano con %) sono commenti ed in particolare: # -- la prima riga, dal secondo carattere in poi, contiene i nomi da attribuire all'array associato a ciascuna colonna # -- la seconda riga, dal secondo carattere in poi, contiene una indicazione del tipo associato a ciascuna colonna def load_file_adv(pathfile='12_structarr_adv.txt'): ##-METTI-QUI-IL-TUO-CODICE-## return #============== # FINE ESERCIZI #============== # NON MODIFICARE DA QUI IN POI!!!!!!!! # FUNZIONE test() usata in main() per stampare # cosa restituisce ciascuna funzione vs. cosa dovrebbe restituire quella corretta def test(got, expected): if got == expected: prefix = 'OK ' print('OK') else: prefix = 'KO ' print('%s restituisce: %s, risultato atteso: %s' % (prefix, repr(got), repr(expected))) def testnparray(got, expected): if (got != None) and (got.dtype == expected.dtype) and np.array_equal(got,expected) : prefix = 'OK ' print('OK') else: prefix = 'KO' print('%s\n restituisce:\n %s \n risultato atteso:\n %s' % (prefix, repr(got), repr(expected))) def testnparrayequal(got, expected,tol=1e-6): if (got == None) or (got.dtype != expected.dtype) or np.any(np.abs(got-expected))>tol : prefix = 'KO' print('%s\n restituisce:\n %s \n risultato atteso:\n %s' % (prefix, repr(got), repr(expected))) return else: prefix = 'OK ' print('OK') return def testnparraynotequal(got, expected): if (got != None) and (got.dtype == expected.dtype) and np.all(got==expected): prefix = 'OK ' print('OK') return else: prefix = 'KO' print('%s\n restituisce:\n %s \n risultato atteso:\n %s' % (prefix, repr(got), repr(expected))) return def test_float(got,expected,eps=1.e-6): if got == None: print('KO restituisce: None, risultato atteso: %s' % (repr(expected))) return if abs(got-expected)< eps: prefix = 'OK ' print('OK') else: #print('KO') prefix = 'KO ' print('%s restituisce: %s, risultato atteso: %s' % (prefix, repr(got), repr(expected))) # chiama le funzioni-soluzione con argomenti fissati e # confronta i risultati con quelli attesi def main(): print('') print('creaarray2D') a = creaarray2D(6) testnparray(a , np.array([[ 0, 1, 2, 3, 4, 5],[10, 11, 12, 13, 14, 15],[20, 21, 22, 23, 24, 25],[30, 31, 32, 33, 34, 35],[40, 41, 42, 43, 44, 45],[50, 51, 52, 53, 54, 55]],dtype=np.int16)) testnparray(creaarray2D(3),np.array([[ 0, 1, 2],[10, 11, 12],[20, 21, 22]],dtype=np.int16)) print('') print('creaarray3D') testnparray(creaarray3D(3),np.array([[[ 0. , 1. , 2.],[ 10. , 11. , 12.],[ 20. , 21. , 22.],], [[ 100. , 101. ,102.],[ 110. , 111. ,112.],[ 120. , 121. ,122.],], [[ 200. , 201. ,202.], [ 210. , 211. ,212.], [ 220. , 221. ,222.],]])) testnparray(creaarray3D(4),np.array([[[ 0. , 1. , 2. ,3. ],[ 10. , 11. , 12. , 13.],[ 20. , 21. , 22. , 23.],[ 30. , 31. , 32. , 33.]], [[ 100. , 101. ,102. ,103.],[ 110. , 111. ,112. , 113.],[ 120. , 121. ,122. ,123.],[ 130. , 131. , 132. , 133.]], [[ 200. , 201. ,202. ,203.], [ 210. , 211. ,212., 213.],[ 220. , 221. ,222. ,223.],[ 230. , 231. , 232. , 233.]], [[ 300. , 301. ,302. ,303.], [ 310. , 311. ,312., 313.],[ 320. , 321. ,322. ,323.],[ 330. , 331. , 332. , 333.]]])) print('') print('mezzaemezza') testnparray(mezzaemezza(2,3),np.array([[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1]])) testnparray(mezzaemezza(4,2),np.array([[0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]])) print('') print('estrai_colonna_2Darray') testnparray(estrai_colonna_2Darray(np.arange(25).reshape(5,5),2),np.array([ 2, 7, 12, 17, 22])) print('') print('estrai_colonna_2Darray_2') testnparray(estrai_colonna_2Darray_2(np.arange(25).reshape(5,5),2),np.array([[ 2],[ 7],[12],[17],[22]])) #scrivo il file necessario per il test with open('12_structarr.txt','wt') as fl: fl.write('%rango\t lemma\t frequenza\tdispersione\n%int S10 int float\n21\t\t they\t\t\t 1865844\t\t0.96\n42\t\t her\t\t\t\t 969591\t\t0.91\n49\t\t as\t\t\t\t 829018\t\t0.95\n7\t\t to\t\t \t 6332195\t\t0.98\n63\t\t take\t\t\t 670745\t\t0.97\n14\t\t you\t\t\t\t 3085642\t\t0.92\n35\t\t go\t\t\t\t 1151045\t\t0.93\n56\t\t think\t\t\t 772787\t\t0.91\n28\t\t not\t\t\t\t 1638883\t\t0.98\n') print('') print('load_file_base') try: dati = load_file_base() except Exception as e: print(e) if (dati != None) : testnparray(dati['rango'],np.array([21, 42, 49, 7, 63, 14, 35, 56, 28])) testnparraynotequal(dati['lemma'],np.array([b'they', b'her', b'as', b'to', b'take', b'you', b'go', b'think', b'not'],dtype='S10')) testnparray(dati['frequenza'],np.array([1865844, 969591, 829018, 6332195, 670745, 3085642, 1151045, 772787, 1638883])) testnparrayequal(dati['dispersione'],np.array([0.96, 0.91, 0.95, 0.98, 0.97, 0.92, 0.93, 0.91, 0.98])) else: print(" K0: dati e' None") #scrivo il file necessario per i test with open('12_structarr_adv.txt','wt') as fl: fl.write('%r\t l\t h f\t d\n%i1 S10 f4 i4 f8\n21\t\t they\t\t 22. 1865844\t\t1e+16\n42\t\t her\t\t\t 12 969591\t\t 0.91\n49\t\t as\t\t\t 1 829018\t\t 0.95\n7\t\t to\t\t 1\t 6332195\t\t0.98\n63\t\t take\t\t 2. 670745\t\t0.97\n14\t\t you\t\t\t 1e-5 3085642\t\t0.92\n35\t\t go\t\t\t 5 1151045\t\t0.93\n56\t\t think\t\t 5 772787\t\t 0.91\n28\t\t not\t\t\t 6 1638883\t\t1e-15\n') print('') print('load_file_adv') try: dati = load_file_adv() except Exception as e: print(e) if (dati != None) : print("dati['r'] : ",end='') testnparray(dati['r'],np.array([21, 42, 49, 7, 63, 14, 35, 56, 28], dtype=np.int8)) print("dati['l'] : ",end='') testnparraynotequal(dati['l'],np.array([b'they', b'her', b'as', b'to', b'take', b'you', b'go', b'think', b'not'],dtype='S10')) print("dati['f'] : ",end='') testnparray(dati['f'],np.array([1865844, 969591, 829018, 6332195, 670745, 3085642, 1151045, 772787, 1638883], dtype=np.int32)) print("dati['d'] : ",end='') testnparrayequal(dati['d'], np.array([ 1.0e+16, 0.91, 0.95, 0.98, 0.97, 0.92, 0.93, 0.91,1.0e-15], dtype=np.float64)) print("dati['h'] : ",end='') testnparrayequal(dati['h'],np. array([ 2.2e+01, 1.2e+01, 1.0e+00,1.0e+00,2.0e+00, 9.99999975e-06,5.00e+00,5.e+00,6.0e+00], dtype=np.float32)) else: print(" K0: dati e' None") #scrivo il file necessario per i test with open('12_structarr_adv_2.txt','wt') as fl: fl.write('%rr\t ll\t ht \n%i2 S20 f4 \n21\t\t they\t\t 22. \n42\t\t her\t\t\t 12 \n49\t\t as\t\t\t 1 \n7\t\t to\t\t 1\t \n63\t\t take\t\t 2. \n14\t\t you\t\t\t 1e-5 \n35\t\t go\t\t\t 5 \n56\t\t think\t\t 5 \n28\t\t not\t\t\t 6 \n') try: dati = load_file_adv('12_structarr_adv_2.txt') except Exception as e: print(e) if (dati != None) : print() print("dati['rr'] : ",end='') testnparray(dati['rr'],np.array([21, 42, 49, 7, 63, 14, 35, 56, 28], dtype=np.int16)) print("dati['ll'] : ",end='') testnparraynotequal(dati['ll'],np.array([b'they', b'her', b'as', b'to', b'take', b'you', b'go', b'think', b'not'],dtype='S20')) print("dati['ht'] : ",end='') testnparrayequal(dati['ht'],np. array([ 2.2e+01, 1.2e+01, 1.0e+00,1.0e+00,2.0e+00, 9.99999975e-06,5.00e+00,5.e+00,6.0e+00], dtype=np.float32)) else: print(" K0: dati e' None") # Standard boilerplate to call the main() function. if __name__ == '__main__': main()