#!/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+++ # Le funzioni devono restituire il risultato corretto # 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 il prefisso OK e la soluzione # esercizio 1 # OK restituisce: [98, 55, 10, 8, 2], risultato atteso: [98, 55, 10, 8, 2] #=============== #INIZIO ESERCIZI #=============== #------------------A---------------- # bomboloni # Dato un numero intero di bomboloni restituire una stringa con il seguente formato: # Numero di bomboloni: # dove è il numero passato come parametro # Se il numero di bomboloni è superiore o uguale a 10 usare # la stringa 'troppi!' invece del numero # quindi bomboloni(5) restituisce 'Numero di bomboloni: 5' # invece bomboloni(23) restituisce 'Numero di bomboloni: troppi!' def bomboloni(count): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------B---------------- # B. both_ends # Data una stringa s, restituisce una stringa fatta # dai primi 2 e gli ultimi 2 caratteri della stringa originale, # 'spring' diventa 'spng'. Tuttavia, se la lunghezza della stringa # è inferiore a 2, invece restituisce una stringa vuota. def both_ends(s): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------C---------------- # C. fix_start # Data una stringa s, restituisce una stringa # dove tutte le occorrenze del suo primo carattere sono # cambiate in '*', ad eccezione del primo carattere stesso. # Ad esempio 'babble' diventa "ba**le" # Si assume che la stringa siaè di lunghezza 1 o più. # Suggerimento: s.replace (stra, strB) restituisce una versione della stringa s # dove tutte le istanze di stra sono sostituite da strB. def fix_start(s): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------D---------------- # D. MixUp # Date le stringhe a e b, restituisce una singola stringa con a e b separate # da uno spazio ' ', ad eccezione di scambiare i primi 2 caratteri di ogni stringa. # ad esempio # 'mix', pod' -> 'pox mid' # 'dog', 'dinner' -> 'dig donner' # si assume che a and b abbiano lunghezza 2 o superiore. def mix_up(a, b): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------E---------------- # E. verbing # Data una stringa, se la sua lunghezza è almeno 3, # aggiunge 'ing' alla fine. # a meno che non si conclude già in 'ing', nel qual caso # aggiunge 'ly'. # Inoltre, se la lunghezza della stringa è inferiore a 3, lasciarla invariato. # Restituisce la stringa risultante. def verbing(s): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------F---------------- # F. not_bad # Data una stringa, trovare la prima occorrenza della # sottostringa 'not' e 'bad'. # Se il 'not' precede il 'bad', sostituire # l'intera sottostringa # 'not' ...'bad' # con # 'good'. # Restituisce la stringa risultante. # Quindi 'This dinner is not that bad!' # diventa # 'This dinner is good!' def not_bad(s): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------G---------------- # G. front_back # Date 2 stringhe, a e b, dividere ciascuna stringa in due metà: # - Se la lunghezza è pari, la prima (front) e la seconda (back) metà hanno la stessa lunghezza. # - Se la lunghezza è dispari, diremo che il carattere in più va nella prima metà. # (Esempio 'abcde', la prima metà è 'abc', la seconda metà 'de') # Restituire quindi una stringa della forma # a-front + b-front + a-back + b-back def front_back(a, b): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------H---------------- # H. test_ascii # data una stringa s in input # restituire True se s e' composta da soli caratteri ASCII # restituire False altrimenti # Esempi: # >>>test_ascii('pippo') # True # >>>test_ascii('perché') # False # >>>test_ascii('gamma maiusc: \N{GREEK CAPITAL LETTER GAMMA}') # False def test_ascii(s): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------I---------------- # getunicodes(bs,enc) # dati: # - bs un oggetto bytes # - enc una stringa che indica un encoding # restituire una lista che contiene le stringhe in formato esadecimale # che identificano il code point dei caratteri rappresentati in bs secondo # l'encoding enc # # Esempi: # >>> getunicodes(bytes([112, 101, 114, 99, 104, 195, 169] , 'utf-8') # ['0x70', '0x65', '0x72', '0x63', '0x68', '0xe9'] # >>> getunicodes('perché'.encode(encoding='utf-8') , 'utf-8') # ['0x70', '0x65', '0x72', '0x63', '0x68', '0xe9'] def getunicodes(bs,enc): ##-METTI-QUI-IL-TUO-CODICE-## return #------------------L---------------- # testbytelength(s,enc1,enc2) # dati: # - una stringa s # - enc1,enc2 due stringhe che indicano un encoding # restituire una tupla di tre elementi: # - il primo contiene una variabile bool che ci dice se la stringa è # codificata secondo i due encoding con lo stesso numero di bytes # - il secondo ed i terzo contengono il numero di bytes in cui la stringa è codificata rispettivamente usando enc1 ed enc2 # # Esempi: # >>> testbytelength('perché','utf-8','latin-1') # (False, 7, 6) # >>> testbytelength('perché','utf-8','utf-16') # (False, 7, 14) # >>> testbytelength('percome','utf-8','latin-1') # (True, 7, 7) # >>> testbytelength('percome','utf-8','utf-16') # (False, 7, 16) def testbytelength(s,enc1,enc2): ##-METTI-QUI-IL-TUO-CODICE-## return #============= #FINE ESERCIZI #============= # 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 ' else: 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('bomboloni') # Each line calls donuts, compares its result to the expected for that call. test(bomboloni(4), 'Numero di bomboloni: 4') test(bomboloni(9), 'Numero di bomboloni: 9') test(bomboloni(10), 'Numero di bomboloni: troppi!') test(bomboloni(99), 'Numero di bomboloni: troppi!') print() print('both_ends') test(both_ends('spring'), 'spng') test(both_ends('Hello'), 'Helo') test(both_ends('a'), '') test(both_ends('xyz'), 'xyyz') print() print('fix_start') test(fix_start('babble'), 'ba**le') test(fix_start('aardvark'), 'a*rdv*rk') test(fix_start('google'), 'goo*le') test(fix_start('donut'), 'donut') print() print('mix_up') test(mix_up('mix', 'pod'), 'pox mid') test(mix_up('dog', 'dinner'), 'dig donner') test(mix_up('gnash', 'sport'), 'spash gnort') test(mix_up('pezzy', 'firm'), 'fizzy perm') print() print('verbing') test(verbing('hail'), 'hailing') test(verbing('swiming'), 'swimingly') test(verbing('do'), 'do') print() print('not_bad') test(not_bad('This movie is not so bad'), 'This movie is good') test(not_bad('This dinner is not that bad!'), 'This dinner is good!') test(not_bad('This tea is not hot'), 'This tea is not hot') test(not_bad("It's bad yet not"), "It's bad yet not") print() print('front_back') test(front_back('abcd', 'xy'), 'abxcdy') test(front_back('abcde', 'xyz'), 'abcxydez') test(front_back('Kitten', 'Donut'), 'KitDontenut') print() print('test_ascii') test(test_ascii('pippo'),True) test(test_ascii('perché'),False) test(test_ascii('gamma maiusc: \N{GREEK CAPITAL LETTER GAMMA}'),False) print() print('getunicodes') test(getunicodes(bytes([112, 101, 114, 99, 104, 195, 169]) , 'utf-8'), ['0x70', '0x65', '0x72', '0x63', '0x68', '0xe9']) test(getunicodes('perché'.encode(encoding='utf-8') , 'utf-8'), ['0x70', '0x65', '0x72', '0x63', '0x68', '0xe9']) test(getunicodes('Heta = \N{GREEK CAPITAL LETTER HETA}, Gamma= \N{GREEK CAPITAL LETTER GAMMA}'.encode(encoding='utf-16'), 'utf-16'), ['0x48', '0x65', '0x74', '0x61', '0x20', '0x3d', '0x20', '0x370', '0x2c', '0x20', '0x47', '0x61', '0x6d', '0x6d', '0x61', '0x3d', '0x20', '0x393']) ##NB: il numero di bytes è diverso dal numero dei caratteri print() print('testbytelength') test(testbytelength('perché','utf-8','latin-1'),(False, 7, 6)) test(testbytelength('perché','utf-8','utf-16'),(False, 7, 14)) test(testbytelength('percome','utf-8','latin-1'),(True, 7, 7)) test(testbytelength('percome','utf-8','utf-16'),(False, 7, 16)) if __name__ == '__main__': main()