









Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!










ORD( ) > converte una stringa nel numero corrispondente : Ord(‘A’) = 65 CHR( ) > converte un numero nella lettera corrispondente : Chi ( 90) = ‘Z’ A.find( ) > per cercare la posizione in una stringa. - se non la contiene CARATTERI ALLINEATI: def chr_align0( a, b ): i, j = 0 , 0 print(a) while j < len(b) and i < len(a): if a[i] == b[j]: print( a[i], end='' ) i, j = i+1, j+ else : print(' ', end='') i = i+ if j < len(b): print('no match’)
t = [] ‘'.join(t) Per avere questo >a rit< anziché >['a', ' ', ' ', ' ', 'r', 'i', ’t']<
del a[ 2 ]
a = list(range( 10 )) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
c = a[:] id(c) != id(a) Con uguale id() Se invece facciamo c = a id(c) == id (a) Sort Sorted(list, key) > ex. Key=len oppure reverse=True Tuples are immutable
2-D con Tuple di coordinate R, C = 0 , 0 for p in P: if p[ 0 ] > C: C = p[ 0 ] if p[ 1 ] > R: R = p[ 1 ] next_point = 0 # P[next_point] is the next point to be placed for y in range(R+1): for x in range(C+1): p = P[next_point] # x and y are the coordinates of p? if x == p[ 0 ] and y == p[ 1 ]: print(p[ 2 ], end='') next_point = next_point+1 # consider the next point if next_point == len(P): break else : print(' ', end='') print() # a new line after row y Binary search
we can provide a sub-linear time algorithm called Binary search. def binary_search(a, k): n = len(a) l, r = 0 , n- while r >= l: c = int((l+r)/2) if a[c] == k: return True if k < a[c]: r = c- else : l = c+ return False binary_search(a, k=1) True Serve per analizzare liste particolarmente lunghe onde evitare che il costo computazionale sia elevatissimo che corrispondere a log n ( worst case )
INTERSEZIONE LISTE COSTO LINEARE: a = [ 1 , 4 , 0 , 7 , 2 , 3 , 9 , 12 , 10 ] b = [ 2 , 1 , 10 , 0 , 8 , 3 , 1 , 7 ] bd = {} #dizionario vuoto for x in b: bd[x] = 0 _#linear cost creando un dizionario che ha per chiavi i valori di b
c = [] for x in a: if x in bd: c.append(x) Poiché x in bd richiede un costo costante, il costo dell'algoritmo è lineare. C è l’intersezione
d.items()mi restituisce tutti gli eletti del dizionario Ex: dict_items([('a', 2), ('n', 5), ('i', 3), ('t', 4), ('r', 3), ('o', 5), ('d', 1), ('u', 1), ('c', 1), ('p', 2), ('g', 2), ('m', 2), ('y', 1), ('h', 1)]) Devo convertirlo in lista se voglio sortare i values e non le chiavi come farebbe normalmente a = list(d.items())
Questa funzione permette se usata come chiave di sort di tenere in considerazione il valore sorted(a, key = k) Per contare solo uno dei due elementi del dizonario( Key : Value) for k,v in d:
APRIRE DOCUMENTI f = open('mark_twain.txt', ‘r’) <-PORTARLO SU PYTHON t = f.read() <- APRIRLO EFFETTIVAMENTE X LEGGERE O SCRIVE
if x.isalpha(): # only char that are letters x = x.lower() # if uppercase it is made lowercase if x in d: d[x] = d[x] + 1 # d[x] is updated else : d[x] = 1 # x is introduced in d
for l, n in a: print(l, int(100n/tl)’#') Libreria Matplot import matplotlib.pyplot as plt Costruzione del diagramma: plt.bar(['a', 'b', 'c'], [ 10 , 4 , 11 ]) [a,b,c, sono i nomi colonne; 10,4,11, i rispettivi valori] #Usare i dati percentuali del documento per diagramma della frequenza delle lettere x, y = [], [] for l, n in a: x.append(l) y.append(100*n/tl)
import numpy as np a = np.array([ 1 , 2 , 3 , 4 , 5 ]) print(a) [1 2 3 4 5 ] b = a/ 2 [0.5 1. 1.5 2. 2.5] [1 2 3 4 5 ] Le dimensioni dell’array si controllano con: a.shape Per fare operazioni tra loro devono avere stesse dimensioni Gli array hanno più dimensioni Ritornando a : y1 = [] for i in y: y1.append(I/106) Una soluzione più veloce con numby è : np.array(y)/10 6
CLEAN WORD SENZA NULLA SOLO LETTERE def clean_word(a): w = '' i = 0 while i < len(a) and not a[i].isalpha(): i += 1 # i points to the leftmost alphabetic character j = len(a)- while j >= 0 and not a[j].isalpha(): j -= 1 # y points to the rightmost alphabetic character w = a[i:j+1] # w is considered a word if all chars in w are alphabetic, otherwise is discarded if w.isalpha(): return w return None PER IL CONTEGGIO DI PAORLE SENZA SEGNI d = {} f = open('mark_twain.txt', 'r') for t in f: for x in t.split(): x = x.lower() # if uppercase it is made lowercase x = clean_word(x) if x in d: d[x] = d[x] + 1 # d[x] is updated else : d[x] = 1 # x is introduced in d
Recursive binary search def binarysearch(a, k, lx = 0 , rx = None ): if rx == None : rx = len(a) if lx < rx: cx = int((lx+rx-1)/2) if a[cx] == k: return cx elif k < a[cx]: return binarysearch(a, k, lx, cx) else : return binarysearch(a, k, cx+1, rx) else : return - CLASSES OPERAZIONI POSSIBILI:
RANDOM FUNCTION random. randint ( a , b ) Return a random integer N such that a <= N <= b. random. randrange ( start , stop [, step ]) Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object. random. random () Return the next random floating point number in the range [0.0, 1.0). random. uniform ( a , b ) Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a. random. choice ( seq ) Return a random element from the non-empty sequence ( list ). If seq is empty, raises IndexError.
Importing files on Pandas group_c = pd.read_csv('2019fifa-wwc-c.csv') In [17]: group_c Out[17]: Filtering of rows In [18]: group_c.Round == 2 Out[18]: 0 False 1 False 2 True 3 True 4 False 5 False Name: Round, dtype: bool
In [19]: group_c[ group_c.Round == 2 ] Out[19]: Round Team1 Score1 Team2 Score 0 1 Australia 1 Italy 2 1 1 Brazil 3 Jamaica 0 2 2 Australia 3 Brazil 2 3 2 Jamaica 0 Italy 5 4 3 Jamaica 1 Australia 4 5 3 Italy 0 Brazil 1 Round Team1 Score1 Team2 Score 2 2 Australia 3 Brazil 2 3 2 Jamaica 0 Italy 5
In [21]: australia = group_c[(group_c.Team1 == 'Australia' )| (group_c.Team2 == 'Australia')] The DataFrame returned by the filtering operation can be assigned to a new variable. In [23]: australia Out[23]: EX. Add a new column containing the winner of each match. In [27]: winners = [] In [28]: for i, x in group_c.iterrows(): if x.Score1 > x.Score2: winners.append(x.Team1) elif x.Score1 < x.Score2: winners.append(x.Team2) else : winners.append('') NOTA BENE! .iterrows(): <- Serve a lavorare su righe e colonne ecco perché scrivi for i, x in .iterrows perché i sono le righe e x le colonne Round Team1 Score1 Team2 Score 0 1 Australia 1 Italy 2 2 2 Australia 3 Brazil 2 4 3 Jamaica 1 Australia 4