STRING TO LIST
import re
def string2listdict(s):
    lista = []
    stud = s.split("\n")
    for elem in stud:
        esami = dict()
        for x in re.finditer("(\w+)=(\d+)", elem):
            if (x.group(1)!= "student"):
                esami[x.group(1)] = x.group(2)
        lista.append(esami)
    return lista
s = "student=1, pds=20, dm=30\nstudent=2, log=28, pds=30"
print(string2listdict(s))
Insiemi
A sequence of integer sets is a list , where and, for ,is a set of integers. Given two sequences of integer sets and , we say that is a subsequence of if:
Write a Python function subseq(S, T) that returns True iff S is a subsequence of T
def SubSeq(S,T):
    i=0
    for elem in S:
        while(i<len(T) and not elem.issubset(T[i])):
            i+=1
        if i==len(T):
            return False
        i+=1
    return True
S=[{1,2},{3},{2,3}]
T=[{1,2,3},{1,2,3},{1},{1,3},{2},{2,4},{2,3}]
SubSeq(S,T)
#OPPURE
def SubSeq(S,T):
    x=0
    for i in range(len(S)):
        for j in range(x,len(T)):
        
10S=[{1,2},{3},{2,3}]
T=[{1,2,3},{1,2,3},{1},{1,3},{2},{2,4},{2,3}]
Z=[{2},{1,2,3},{1},{1,3},{2},{2,4}]
SubSeq(S,Z)
POWERSET() trova l'insieme delle parti di un insieme (tutti i suoi sottoinsiemi)
def powerSet(S):
    a = list(S)
    n = len(S)
    res = set()
    for i in range(2**n):
        pow2 = 1
        subset = set()
        for k in range(n):
            if i & pow2 != 0: # (i//pow2)%2==1
                subset.add(a[k])
            pow2 *= 2
        res.add(frozenset(subset))
    return res
S = {1,2,3}
print(powerSet(S))
# OPPURE con INSIEMI
def subsets(S):
    l = len(S)
    if l == 0:
        return {frozenset()} # non-modifiable empty-set
    elem = S.pop()
    PS = subsets(S)
    result = PS | {A | {elem} for A in PS} #bitwise or sta per unione o +
    return result
# OPPURE CON LISTE
def powerSet(s):
    if s==[]:
        return [s]
    else:
        e = s[0]
        t = s[1:]
        pt = powerSet(t)
        fept = [x + [e] for x in pt]
        return pt + fept
ESAME 15/01 powerset e classe
Fai una classe che prende un insieme in input e restituisce il powerset di quell'insieme
from random import randint
class PowerS():
    def
__init__(self):
    self.S = set()
    n = randint(1, 10)
    while(len(self.S) < n):
        self.S.add(randint(-50, 50))
def PowerSet(self):
    a = list(self.S)
    n = len(self.S)
    res = set()
    for i in range(2**n):
        pow2 = 1
        subset = set()
        for k in range(n):
            if i & pow2 != 0:
                subset.add(a[k])
            pow2 *= 2
        res.add(frozenset(subset))
    return res
def __repr__(self):
    return "{}".format(self.S)
PS = PowerS()
print(PS.PowerSet())
print(PS)
MAXIMAL PAIR (ricorsione, bitwise operator)
A pair (x, y) of natural numbers is maximal in a given set of pairs setpairs if it is not dominated by any other pair (w, z) in the set, i.e., it does not hold that: w >= x and z >= y and at least one of the inequalities is strict. Develop a recursive Python function:
- maximalpairs(setpairs) that returns the set of all maximal pairs in setpairs. For instance:
- maximalpairs({ (1, 0), (0, 3), (1, 2) }) shall return {(1, 2), (0, 3)}
- maximalpairs({ (1, 4), (0, 3), (1, 2) }) shall return {(1, 4)}
def
maximalpairs(setpairs):
    # base case: empty set
    if len(setpairs)==0:
        return set()
    
    # pop a pair(x, y) = setpairs.pop()
    
    # recursive call on rest of the set
    maxpairs = maximalpairs(setpairs)
    
    # pairs in maxpairs dominated by (x, y)
    dominated = set()
    
    # scan all elements of maxpairs
    for (w, z) in maxpairs:
        # (x, y) domainated by (w, z)
        if x <= w and y <= z and (x < w or y < z):
            # (x, y) is not maximal, return maxpairs
            # dominated is necessary empty: prove it by induction!
            return maxpairs
        
        # (w, z) dominated by (x, y)
        if w <= x and z <= y and (w < x or z < y):
            # add (w, z) to the dominated pairs
            dominated.add((w, z))
    
    return (maxpairs-dominated) | {(x,y)}
setpairs={(1,2), (0,3), (1,0)}
print(maximalpairs(setpairs))
BITWISE OR MAXAND
from itertools import combinations
def maxand(s,n):
    seq = combinations( list(s), n )
    massimo =0
    for subset in seq:
        bit_and = None
        for num in subset:
            if bit_and == None:
                bit_and = num
            bit_and = bit_and & num
        if massimo <
```bit_and:massimo = bit_andprint(massimo)maxand({2,5,13},1)maxand({2,5,13},2)maxand({2,5,13},3)#oppuredef maxand(S,n):lista=list(S)nuovo=[]for elem in combinations(lista,n):res=0for num in elem:if res==0:res=numelse:res&=numnuovo.append(res)return max(nuovo)maxand({2,5,13},3)TEST 3/04/2019Esercizio 1. usare generalized inclusion-exclusion di tutti i set di LSe considero tre insiemi (quindi con n=3) il principio si manifesterà cosi:def powerSet(s):if s==[]:return [s]else:e = s[0]t = s[1:]pt = powerSet(t)fept = [x + [e] for x in pt]return pt + feptdef intersezione(lista):if not lista:return 0result = set(lista[0])for s in lista[1:]:result &= set(s)return len(result)def incl_excl(lista):for elem in lista:if len(set(elem)) != len(elem):raise ValueErrorfor elem2 in elem:if not isinstance(elem2,int):raise ValueErrorProgramming for Data Science - Python 13subsets=powerSet(lista)res=0for elem in subsets:if len(elem)%2!=0:res+=intersezione(elem)iflen(elem)%2==0:res-=intersezione(elem)return res
lista=[[1,2,3],[7,3,6],[3,4,2]]
incl_excl(lista)
TEST 15/02 ARFFTYPE
def ArffType(lista,n):
    if len(set(lista))<=n:
        return 'enumerated'
    else:
        for elem in lista:
            try:
                float(elem)
            except ValueError:
                return 'string'
        return 'numeric'
print(ArffType(['3','4','1.2','4'],2))
print(ArffType(['3','4','1.2','4'],3))
print(ArffType(['3','hello','1.2','4'],2))
print(ArffType(['3','hello','1.2','4'],4))
Trova tutti gli anagrammi di una parola e inseriscili in una lista
from itertools import permutations
lista=[]
x=input('inserisci stringa:')
string = permutations(x)
for char in set(string):
    lista.append("".join(char))
print(lista)
ES 2 TEST SETTEMBRE
Programming for Data Science - Python 14
def numero_primo(n):
    fattore=2
    primo=1
    while primo and fattore<n:
        if
n%fattore==0:
    primo=0
else:
    fattore+=1
if primo == 0:
    return False
else:
    return True
def risultato_right(lista):
    risultato_rt = 0
    for i in range(len(lista)):
        part = lista[:len(lista)-i]
        part = ''.join(part)
        numero = int(part)
        if numero_primo(numero)!=True:
            return False
        risultato_rt +=1
    return risultato_rt
def risultato_left(lista):
    risultato_lt = 0
    for i in range(len(lista)):
        part = lista[i:]
        part = ''.join(part)
        numero = int(part)
        if numero_primo(numero)!=True:
            return False
        risultato_lt +=1
    return risultato_lt
def truncatable(n):
    n = str(n)
    lista = []
    for elem in n:
        lista.append(elem)
    for x in range(len(lista)):
        if lista[x] == '0':
            return False
    risul1 = risultato_left(lista)
    risul2 = risultato_right(lista)
    if risul1 == len(lista) and risul2 == len(lista):
        return 'both'
    if risul1 == len(lista):
        return 'left'
    if risul2 == len(lista):
        return 'right'
print(truncatable(9137))
print(truncatable(5939))
print(truncatable(137))
print(truncatable(5))
print(truncatable(103))
Programming for Data Science - Python 15
n=input()
while n!='':
    print(n)
    n=input()
Count how often each letter occurs in a string (case-insensitively). Print the
letters with their counts, in order from highest count to lowest count.
Crea una lista in cui inserisci tutte le lettere dell'alfabeto e il loro numero di occorrenze (lista di liste)
def ordina(x):
    return x[1], -ord(x[0])
text = """
Now, it's quite simple to defend yourself against a man armed with a banana. First of all you fo
"""
text=text.lower()
countlist=[]
for i in range(26):
    countlist.append([chr(ord('a')+i),0])
for char in text:
    for i in range(26):
        if char==countlist[i][0]:
            countlist[i][1]+=1
countlist.sort(key=ordina, reverse=True)
countlist
Trova i numeri mancanti in una lista ordinata
#list comprehension
def find_missing(lst):
    return [x for x in range(lst[0], lst[-1]+1) if x not in lst]
#set
def find_missing(lst):
    return sorted(set(range(lst[0]), lst[-1]+1)) - set(lst)
lst = [1, 2, 4, 6, 7, 9, 10]
print(find_missing(lst))
def palindromo(s):
    if len(s) <= 1:
        return True
    if s[0] == s[-1]:
        return palindromo(s[1:-1])
    else:
        return False
print(palindromo("ciao"))
def dispari(lista):
    if len(lista) == 0:
        return []
    if lista[0] % 2 == 1:
        return [lista[0]] + dispari(lista[1:])
    return dispari(lista[1:])
print(dispari([1, 2, 3, 4, 5, 6]))
def fibonacci(n):
    if n == 1 or n == 2:
        return 1
    return (fibonacci(n - 1) + (fibonacci(n - 2)))
print(fibonacci(7))
def somma_liste(lista):
    totale = 0
    for elem in lista:
        if type(elem) == type([]):
            totale = totale + somma_liste(elem)
        else:
            totale = totale + elem
    return totale
lista = [1, 2, [3, 4, 5], [5, 6]]
print(somma_liste(lista))
def sommaric_inversa(lista):
    if len(lista) == 1:
        return lista[0]
    return lista[len(lista) - 1] +
sommaric_inversa(lista[:len(lista)-1])lista=[10,4,2]print(sommaric(lista))#Partendo dal primo elem fino ad arrivare all'utlimodef sommaric(lista):    if len(lista) == 1:        return lista[0]    else:        return lista[0] + somma_ric(lista[1:])print(somma_ric([2, 4, 5, 6, 7]))MINIMO/MASSIMO RICORSIVOProgramming for Data Science - Python 17def minimoLista(lista):    if len(lista) == 1:        return lista[0]    minimo = lista[0]    altri = minimoLista(lista[1:])    return min(minimo, altri)def mass
        Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
- 
            
                ![Riassunto esame Programming for Data Science, prof. Ruggieri, libro consigliato Discrete mathematics and its applications, Rosen]() Riassunto esame Programming for Data Science, prof. Ruggieri, libro consigliato Discrete mathematics and its applic… Riassunto esame Programming for Data Science, prof. Ruggieri, libro consigliato Discrete mathematics and its applic…
- 
            
                ![Esercizi svolti di statistica]() Esercizi svolti di statistica Esercizi svolti di statistica
- 
            
                ![Esercizi circuiti]() Esercizi circuiti Esercizi circuiti
- 
            
                ![Esercizi Informatica Python]() Esercizi Informatica Python Esercizi Informatica Python
 
                     
                                                     
                                                     
                                         
                                        