#!/usr/bin/python -tt #======= #Crediti #======= # esercizi corso di python @ifac-cnr # Esercizi tratti liberamente da: # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Copyright 2010 Google Inc. # 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+++ # UNA VOLTA # Fill in the code for the functions below. main() is already set up # to call the functions with a few different inputs, # printing 'OK' when each function is correct. # The starter code for each function includes a 'return' # which is just a placeholder for your code. # It's ok if you do not complete all the functions, and there # are some additional functions to try in list2.py. #=============== #INIZIO ESERCIZI #=============== # ---------------- # generaLista(num) # ---------------- # num è un intero # genera una lista che va da 0 a num, num compreso # se num < 0 restituisce una lista vuota def generaLista(num): ##-INIZIO-SOLUZIONE-## if num >= 0: return list(range(num+1)) else: return [] ##-FINE-SOLUZIONE-## # ------------------------ # generaLista2(start, end) # ------------------------ # start ed end sono interi # generare una lista che va da start a end, end compreso # se start > end restituisce una lista vuota def generaLista2(start, end): ##-INIZIO-SOLUZIONE-## return list(range(start,end+1)) ##-FINE-SOLUZIONE-## # ------------------------------ # generaLista3(start, end, step) # ------------------------------ # start ed end e step sono interi # generare una lista che va da start a end, end compreso a passi di step # - se step è positivo e se start > end restituisce una lista vuota # - se step è negativo e se start < end restituisce una lista vuota # - gestire il caso step == 0 restituendo una lista vuota # (altrimenti python segnalerebbe errore) def generaLista3(start, end,step): ##-INIZIO-SOLUZIONE-## if step ==0: return [] elif step >0: return list(range(start,end+1,step)) else: return list(range(start,end-1,step)) ##-FINE-SOLUZIONE-## # ------------------------------ # sommaLista(start, end, step) # ------------------------------ # # start ed end e step sono interi # restituire la somma degli elementi della lista restituita # dall'esercizio precedente # suggerimento: # - meglio fare l'esercizio dopo aver risolto il precedente generaLista3 ;-) # - help(sum) def sommaLista(start, end,step): ##-INIZIO-SOLUZIONE-## return sum(generaLista3(start, end,step)) ##-FINE-SOLUZIONE-## # -------------- # sommapari(s,e) # -------------- # s ed e sono interi # la funzione restituisce la somma di tutti i numeri pari # tra s ed e (compreso). # Suggerimento: # - x%2 restituisce 0 se x è un numero pari. # Esempi: # >>> sommapari(3, 7) # 10 # >>> sommapari(5, 12) # 36 def sommapari(s,e): ##-INIZIO-SOLUZIONE-## if s%2==0: return sum(range(s,e+1,2)) else: return sum(range(s+1,e+1,2)) ##-FINE-SOLUZIONE-## # -------- # sort_abs # -------- # Data una lista di interi positivi e negativi generare # la lista ordinata in modo decrescente dei valori assoluti # Sugg.: list comprehension + parametro reversed in funzione sorted def sort_abs(nums): ##-INIZIO-SOLUZIONE-## return sorted([abs(x) for x in nums],reverse=True) ##-FINE-SOLUZIONE-## # ---------- # match_ends # ---------- # Data una lista di stringhe, restituire il numero di stringhe # la cui lunghezza è maggiore o uguale a 2 e che hanno il primo # e l'ultimo carattere uguali. # Nota: Python non ha un operatore ++, ma supporta += def match_ends(words): ##-INIZIO-SOLUZIONE-## n = 0 for w in words: if len(w)>=2 and w[0]==w[-1]: n += 1 return n ##-FINE-SOLUZIONE-## # ------- # front_x # ------- # Data una lista di stringhe, restituire una lista con le stringhe ordinate # tranne il gruppo di quelle che iniziano per x che devono essere restituite per prime # e anch esse ordinate # ad es. con ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] # la funzione deve restituire # ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] def front_x(words): ##-INIZIO-SOLUZIONE-## xstr = [] nstr = [] for w in words: if w[0]=='x': xstr.append(w) else: nstr.append(w) return sorted(xstr) + sorted(nstr) ##-FINE-SOLUZIONE-## # --------- # sort_last(listadiliste) # --------- # data una lista di liste (non vuote ma di lunghezza arbitraria) # restituire una NUOVA lista ordinata in base all'ultimo elemento di ciascuna lista 'interna' # non modificare la listadiliste originaria # ad es. con [[1, 7], [1, 3], [3, 4, 5], [2, 2]] # la funzione deve restituire # [[2, 2], [1, 3), [3, 4, 5], [1, 7]] # Suggerimento: usare il parametro key di sorted ##-INIZIO-OPZIONALE-## def mysort(t): return t[-1] ##-FINE-OPZIONALE-## def sort_last(listadiliste): ##-INIZIO-SOLUZIONE-## return sorted(listadiliste,key=mysort) ##-FINE-SOLUZIONE-## # ------------ # find_indices # ------------ #Trovare gli indici di tutte le occorrenze di 'val' nella lista 'mylist' #ad esempio se val=1 e mylist=[1,3,6,9,1,1,2,1,2] il risultato deve essere [0,4,5,7] def find_indices(mylist,val): ##-INIZIO-SOLUZIONE-## return [i for i, x in enumerate(mylist) if x == val] #oppure return list(filter(lambda i : mylist[i]== val,range(len(mylist)))) ##-FINE-SOLUZIONE-## # nested_list # ----------- # dati il numero di righe nrow e di colonne ncols istanziare # una lista di nrows liste ciascuna con ncols numeri interi # in modo che le righe siano popolate da interi crescenti a partire da 1 # ad esempio con nrows=3 ed ncols=4 # la funzione restituisce # [[1,2,3,4],[5,6,7,8],[9,10,11,12]] def nested_list(nrows,ncols): ##-INIZIO-SOLUZIONE-## return [list(range(num*ncols+1,(num+1)*ncols+1)) for num in range(nrows)] #oppure #return[[i for i in range(num*ncols+1,(num+1)*ncols+1)] for num in range(nrow)] ##-FINE-SOLUZIONE-## # identity_matrix # --------------- # creare la matrice identità con liste annidate (per righe) # ad esempio per n=3 # la funzione restituisce # [[1,0,0],[0,1,0],[0,0,1]] # Suggerimento: list comprehension + operatore ternario def identity_matrix(n): ##-INIZIO-SOLUZIONE-## return [[(1 if i==j else 0) for i in range(n)] for j in range(n)] ##-FINE-SOLUZIONE-## # remove_adjacent(nums) # --------------- # data una lista di numeri restituire una lista in cui tutti gli elementi # adiacenti uguali sono stati ridotti ad un singolo elemento # con [1, 2, 2, 3, 2, 2, 3] la funzione ritorna [1, 2, 3, 2, 3]. # Nota: si può sia restituire una nuova lista sia modificare quella passata come argomento def remove_adjacent(nums): ##-INIZIO-SOLUZIONE-## #determino gli indici dei doppioni adiacenti indici=[] for i in range(1,len(nums)): if nums[i]==nums[i-1]: indici.append(i) #elimino i doppioni adiacenti for i in reversed(indici): nums.pop(i) return nums ##-FINE-SOLUZIONE-## ##-INIZIO-OPZIONALE-## def remove_adjacent2(nums): #soluzione + elegante che implica una singola iterazione result = [] #itero sulla lista e aggiungo ai risultati #l'elemento della lista solo se diverso dall'ultimo #elemento aggiunto ai risultati for num in nums: if len(result) == 0 or num != result[-1]: result.append(num) return result ##-FINE-OPZIONALE-## # linear_merge # ------------ # Date due liste ordinate in ordine crescente, creare e restituire un'unica # lista di tutti gli elementi ordinati. # E' possibile modificare le liste passate come argomenti. # Idealmente l' algoritmo dovrebbe implicare una singola iterazione # su ciascuna lista. # suggerimento: le liste sono ordinate: # confrontare il primo elemento delle due liste # ed aggiungere il più piccolo alla lista da restituire come risultato # (rimuovendolo dalla lista originaria) # continuare fino a che una delle due liste non si svuota def linear_merge(list1, list2): ##-INIZIO-SOLUZIONE-## result = [] # confronto il primo elemento delle due liste # ed aggiungo il più piccolo ai risultati # (rimuovendolo dalla lista originaria) # continuo fino a che una delle due liste non si svuota while len(list1) and len(list2): if list1[0] < list2[0]: result.append(list1.pop(0)) else: result.append(list2.pop(0)) # aggiungo ciò che rimane result.extend(list1) result.extend(list2) return result ##-FINE-SOLUZIONE-## def linear_merge2(list1, list2): return sorted(list1+list2) #============= #FINE ESERCIZI #============= # NON MODIFICARE DA QUI IN POI!!!!!!!! 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 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))) # Calls the above functions with interesting inputs. def main(): print('generaLista') test(generaLista(0) , [0] ) test(generaLista(10) , [0,1,2,3,4,5,6,7,8,9,10] ) test(generaLista(-10) , [] ) print('generaLista2') test(generaLista2(0,0) , [0] ) test(generaLista2(8,10) , [8,9,10] ) test(generaLista2(-10,-7) , [-10,-9,-8,-7] ) test(generaLista2(-7,-10) , [] ) print('generaLista3') test(generaLista3(0,0,2) , [0] ) test(generaLista3(8,13,3) , [8,11] ) test(generaLista3(-10,-2,2) , [-10,-8,-6,-4,-2] ) test(generaLista3(10,1,-3) , [10,7,4,1] ) test(generaLista3(1,10,-3) , [] ) test(generaLista3(10,1,3) , [] ) test(generaLista3(8,13,0) , [] ) print('sommaLista') test(sommaLista(0,0,2) , 0 ) test(sommaLista(8,13,3) , 19 ) test(sommaLista(-10,-2,2) , -30 ) test(sommaLista(10,1,-3) , 22 ) test(sommaLista(10,1,3) , 0 ) test(sommaLista(8,13,0) , 0 ) print('sommapari') test(sommapari(3, 7),10) test(sommapari(5, 12),36) print('sort_abs') test(sort_abs([-10,55,98,-2,8]) , [98,55,10,8,2] ) print('match_ends') test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3) test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2) test(match_ends(['aaa', 'be', 'abc', 'hello']), 1) print('front_x') test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']), ['xaa', 'xzz', 'axx', 'bbb', 'ccc']) test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']), ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']) test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']), ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']) print('sort_last') test(sort_last([(1, 3), (3, 2), (2, 1)]), [(2, 1), (3, 2), (1, 3)]) test(sort_last([(2, 3), (1, 2), (3, 1)]), [(3, 1), (1, 2), (2, 3)]) test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]), [(2, 2), (1, 3), (3, 4, 5), (1, 7)]) print('find_indices') test(find_indices(['bbb', 'ccc', 'bbb', 'xzz', 'bbb'],'bbb'),[0, 2, 4,]) test(find_indices([1,3,6,9,1,1,2,1,2],1),[0,4,5,7]) print('nested_list') test(nested_list(7,8),[[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 31, 32], [33, 34, 35, 36, 37, 38, 39, 40], [41, 42, 43, 44, 45, 46, 47, 48], [49, 50, 51, 52, 53, 54, 55, 56]]) print('identity_matrix') test(identity_matrix(6),[[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]]) print('remove_adjacent') test(remove_adjacent([1, 2, 2, 3, 2, 2, 3]), [1, 2, 3, 2, 3]) test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3]) test(remove_adjacent([]), []) print('linear_merge') test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']), ['aa', 'bb', 'cc', 'xx', 'zz']) test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']), ['aa', 'bb', 'cc', 'xx', 'zz']) test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']), ['aa', 'aa', 'aa', 'bb', 'bb']) ##-INIZIO-OPZIONALE-## print('linear_merge2') test(linear_merge2(['aa', 'xx', 'zz'], ['bb', 'cc']), ['aa', 'bb', 'cc', 'xx', 'zz']) test(linear_merge2(['aa', 'xx'], ['bb', 'cc', 'zz']), ['aa', 'bb', 'cc', 'xx', 'zz']) test(linear_merge2(['aa', 'aa'], ['aa', 'bb', 'bb']), ['aa', 'aa', 'aa', 'bb', 'bb']) import timeit print('test timeit linear_merge') #t0 = timeit.Timer("print('pippo')") t1 = timeit.Timer("linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc'])","from __main__ import linear_merge") t2 = timeit.Timer("linear_merge2(['aa', 'xx', 'zz'], ['bb', 'cc'])","from __main__ import linear_merge2") n=10000 print('esecuzione {0} x linear_merge : {1} s'.format(n,t1.timeit(n))) print('esecuzione {0} x linear_merge2 : {1} s'.format(n,t2.timeit(n))) ##-FINE-OPZIONALE-## if __name__ == '__main__': main()