fondamenti di informatica (elettronici)

47
Fondamenti di Informatica (Elettronici) n-alberi e grafi – Lezione 39 20 gennaio 2021 n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 1 / 24

Upload: others

Post on 15-Oct-2021

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Fondamenti di Informatica (Elettronici)

Fondamenti di Informatica (Elettronici)

n-alberi e grafi – Lezione 39

20 gennaio 2021

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 1 / 24

Page 2: Fondamenti di Informatica (Elettronici)

n-alberi e grafi

1 Alberi binari di ricerca

2 Alberi n-ari

3 Rappresentazioni dei grafi

4 Operazioni topologiche su grafi

5 Noteworthy differences from Python

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 2 / 24

Page 3: Fondamenti di Informatica (Elettronici)

Alberi binari di ricerca

Section 1

Alberi binari di ricerca

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 3 / 24

Page 4: Fondamenti di Informatica (Elettronici)

Alberi binari di ricerca

Algoritmo di ricerca in albero binario ordinatoSi assume che i nodi possano essere ordinati,ad esempio: cognomi ordinatialfabeticamente, oppure codici fiscali.

Un albero binario di ricerca assume che:

tutti i nodi del sottoalbero sinistroabbiano valore minore o eguale allaradicetutti i nodi del sottoalbero destroabbiano valore maggiore

In tal caso si puo’ trovare un elemento (seesiste) oppure verificare la sua non esistenzacon un numero di confronti non superiore alpiu’ lungo cammino sull’albero.

Se l’albero e’ bilanciato, e contiene n nodi,allora tali cammini hanno complessitàO(log n)

algoritmo cerca (x, T)if vuoto(T)

stampa 'x non in T'else

if x = radice(T)ind(x)

elseif x < radice(T)

cerca (x, sinistro(T) )else

cerca (x, destro(T)

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 4 / 24

Page 5: Fondamenti di Informatica (Elettronici)

Alberi binari di ricerca

Algoritmo di ricerca in albero binario ordinatoSi assume che i nodi possano essere ordinati,ad esempio: cognomi ordinatialfabeticamente, oppure codici fiscali.

Un albero binario di ricerca assume che:tutti i nodi del sottoalbero sinistroabbiano valore minore o eguale allaradice

tutti i nodi del sottoalbero destroabbiano valore maggiore

In tal caso si puo’ trovare un elemento (seesiste) oppure verificare la sua non esistenzacon un numero di confronti non superiore alpiu’ lungo cammino sull’albero.

Se l’albero e’ bilanciato, e contiene n nodi,allora tali cammini hanno complessitàO(log n)

algoritmo cerca (x, T)if vuoto(T)

stampa 'x non in T'else

if x = radice(T)ind(x)

elseif x < radice(T)

cerca (x, sinistro(T) )else

cerca (x, destro(T)

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 4 / 24

Page 6: Fondamenti di Informatica (Elettronici)

Alberi binari di ricerca

Algoritmo di ricerca in albero binario ordinatoSi assume che i nodi possano essere ordinati,ad esempio: cognomi ordinatialfabeticamente, oppure codici fiscali.

Un albero binario di ricerca assume che:tutti i nodi del sottoalbero sinistroabbiano valore minore o eguale allaradicetutti i nodi del sottoalbero destroabbiano valore maggiore

In tal caso si puo’ trovare un elemento (seesiste) oppure verificare la sua non esistenzacon un numero di confronti non superiore alpiu’ lungo cammino sull’albero.

Se l’albero e’ bilanciato, e contiene n nodi,allora tali cammini hanno complessitàO(log n)

algoritmo cerca (x, T)if vuoto(T)

stampa 'x non in T'else

if x = radice(T)ind(x)

elseif x < radice(T)

cerca (x, sinistro(T) )else

cerca (x, destro(T)

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 4 / 24

Page 7: Fondamenti di Informatica (Elettronici)

Alberi binari di ricerca

Algoritmo di ricerca in albero binario ordinatoSi assume che i nodi possano essere ordinati,ad esempio: cognomi ordinatialfabeticamente, oppure codici fiscali.

Un albero binario di ricerca assume che:tutti i nodi del sottoalbero sinistroabbiano valore minore o eguale allaradicetutti i nodi del sottoalbero destroabbiano valore maggiore

In tal caso si puo’ trovare un elemento (seesiste) oppure verificare la sua non esistenzacon un numero di confronti non superiore alpiu’ lungo cammino sull’albero.

Se l’albero e’ bilanciato, e contiene n nodi,allora tali cammini hanno complessitàO(log n)

algoritmo cerca (x, T)if vuoto(T)

stampa 'x non in T'else

if x = radice(T)ind(x)

elseif x < radice(T)

cerca (x, sinistro(T) )else

cerca (x, destro(T)

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 4 / 24

Page 8: Fondamenti di Informatica (Elettronici)

Alberi binari di ricerca

Algoritmo di ricerca in albero binario ordinatoSi assume che i nodi possano essere ordinati,ad esempio: cognomi ordinatialfabeticamente, oppure codici fiscali.

Un albero binario di ricerca assume che:tutti i nodi del sottoalbero sinistroabbiano valore minore o eguale allaradicetutti i nodi del sottoalbero destroabbiano valore maggiore

In tal caso si puo’ trovare un elemento (seesiste) oppure verificare la sua non esistenzacon un numero di confronti non superiore alpiu’ lungo cammino sull’albero.

Se l’albero e’ bilanciato, e contiene n nodi,allora tali cammini hanno complessitàO(log n)

algoritmo cerca (x, T)if vuoto(T)

stampa 'x non in T'else

if x = radice(T)ind(x)

elseif x < radice(T)

cerca (x, sinistro(T) )else

cerca (x, destro(T)

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 4 / 24

Page 9: Fondamenti di Informatica (Elettronici)

Alberi binari di ricerca

Alberi binari di ricerca

FILE A INDICI

Gli alberi binari di ricerca sono usati come indici su grandi archivi ordinati

Per indicare tali tipi di archivi si parla anche di file a indici

In un archivio di questo tipo la ricerca di un elemento si esegue in un tempologaritmico con il numero di elementi (es: 20 accessi per trovare unelemento in un archivio di un milione di elementi)

La ricerca resta efficiente se l’albero di ricerca resta bilanciato.

L’inserzione/cancellazione di elementi deve mantenere bilanciato l’albero,eventualmente “ruotando” dei sottoalberi

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 5 / 24

Page 10: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Section 2

Alberi n-ari

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 6 / 24

Page 11: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Albero n-ario (Tree)

DEFINIZIONE

Tipo astratto <S, F, C>, dove

S = < Tree, nodo, boolean >,F = < root, parent, firstChild, rightSibling, attach, build, null >,C = < albero_vuoto >

con Tree Albero ordinato detto dominio di interesse, e dove

root : Tree -+ nodo;parent : nodo x Tree -+ nodo;firstChild : nodo x Tree -+ nodo;rightSibling : nodo x Tree -+ nodo;attach : nodo x Tree -+ Tree;build : Tree x Tree -4 Tree;null : Tree -+boolean;

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 7 / 24

Page 12: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Descrizione (semantica) delle operazioni

root definita sugli alberi non vuoti; restituisce la radice;

parent restituisce il padre del nodo n, se presente in T ; se n 6∈ Toppure n è radice, restituisce il simbolo speciale >

firstChild restituisce il primogenito del nodo n; se n 6∈ T oppure n èfoglia, restituisce il simbolo speciale >

rightSibling restituisce il prossimo fratello del nodo n; se n 6∈ T oppure n èultimo figlio, restituisce il simbolo speciale >

attach attacca il nodo n come radice di Tbuild assume in ingresso due alberi; restituisce l’albero costruito

attaccando la radice del secondo argomento come ultimofiglio della radice del primo argomento (gli interi alberi restanoattaccati)

null prende in ingresso un valore T ∈ Tree; restituisce true se Tè l’albero vuoto; false altrimenti.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 8 / 24

Page 13: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Descrizione (semantica) delle operazioni

root definita sugli alberi non vuoti; restituisce la radice;parent restituisce il padre del nodo n, se presente in T ; se n 6∈ T

oppure n è radice, restituisce il simbolo speciale >

firstChild restituisce il primogenito del nodo n; se n 6∈ T oppure n èfoglia, restituisce il simbolo speciale >

rightSibling restituisce il prossimo fratello del nodo n; se n 6∈ T oppure n èultimo figlio, restituisce il simbolo speciale >

attach attacca il nodo n come radice di Tbuild assume in ingresso due alberi; restituisce l’albero costruito

attaccando la radice del secondo argomento come ultimofiglio della radice del primo argomento (gli interi alberi restanoattaccati)

null prende in ingresso un valore T ∈ Tree; restituisce true se Tè l’albero vuoto; false altrimenti.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 8 / 24

Page 14: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Descrizione (semantica) delle operazioni

root definita sugli alberi non vuoti; restituisce la radice;parent restituisce il padre del nodo n, se presente in T ; se n 6∈ T

oppure n è radice, restituisce il simbolo speciale >firstChild restituisce il primogenito del nodo n; se n 6∈ T oppure n è

foglia, restituisce il simbolo speciale >

rightSibling restituisce il prossimo fratello del nodo n; se n 6∈ T oppure n èultimo figlio, restituisce il simbolo speciale >

attach attacca il nodo n come radice di Tbuild assume in ingresso due alberi; restituisce l’albero costruito

attaccando la radice del secondo argomento come ultimofiglio della radice del primo argomento (gli interi alberi restanoattaccati)

null prende in ingresso un valore T ∈ Tree; restituisce true se Tè l’albero vuoto; false altrimenti.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 8 / 24

Page 15: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Descrizione (semantica) delle operazioni

root definita sugli alberi non vuoti; restituisce la radice;parent restituisce il padre del nodo n, se presente in T ; se n 6∈ T

oppure n è radice, restituisce il simbolo speciale >firstChild restituisce il primogenito del nodo n; se n 6∈ T oppure n è

foglia, restituisce il simbolo speciale >rightSibling restituisce il prossimo fratello del nodo n; se n 6∈ T oppure n è

ultimo figlio, restituisce il simbolo speciale >

attach attacca il nodo n come radice di Tbuild assume in ingresso due alberi; restituisce l’albero costruito

attaccando la radice del secondo argomento come ultimofiglio della radice del primo argomento (gli interi alberi restanoattaccati)

null prende in ingresso un valore T ∈ Tree; restituisce true se Tè l’albero vuoto; false altrimenti.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 8 / 24

Page 16: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Descrizione (semantica) delle operazioni

root definita sugli alberi non vuoti; restituisce la radice;parent restituisce il padre del nodo n, se presente in T ; se n 6∈ T

oppure n è radice, restituisce il simbolo speciale >firstChild restituisce il primogenito del nodo n; se n 6∈ T oppure n è

foglia, restituisce il simbolo speciale >rightSibling restituisce il prossimo fratello del nodo n; se n 6∈ T oppure n è

ultimo figlio, restituisce il simbolo speciale >attach attacca il nodo n come radice di T

build assume in ingresso due alberi; restituisce l’albero costruitoattaccando la radice del secondo argomento come ultimofiglio della radice del primo argomento (gli interi alberi restanoattaccati)

null prende in ingresso un valore T ∈ Tree; restituisce true se Tè l’albero vuoto; false altrimenti.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 8 / 24

Page 17: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Descrizione (semantica) delle operazioni

root definita sugli alberi non vuoti; restituisce la radice;parent restituisce il padre del nodo n, se presente in T ; se n 6∈ T

oppure n è radice, restituisce il simbolo speciale >firstChild restituisce il primogenito del nodo n; se n 6∈ T oppure n è

foglia, restituisce il simbolo speciale >rightSibling restituisce il prossimo fratello del nodo n; se n 6∈ T oppure n è

ultimo figlio, restituisce il simbolo speciale >attach attacca il nodo n come radice di Tbuild assume in ingresso due alberi; restituisce l’albero costruito

attaccando la radice del secondo argomento come ultimofiglio della radice del primo argomento (gli interi alberi restanoattaccati)

null prende in ingresso un valore T ∈ Tree; restituisce true se Tè l’albero vuoto; false altrimenti.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 8 / 24

Page 18: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Descrizione (semantica) delle operazioni

root definita sugli alberi non vuoti; restituisce la radice;parent restituisce il padre del nodo n, se presente in T ; se n 6∈ T

oppure n è radice, restituisce il simbolo speciale >firstChild restituisce il primogenito del nodo n; se n 6∈ T oppure n è

foglia, restituisce il simbolo speciale >rightSibling restituisce il prossimo fratello del nodo n; se n 6∈ T oppure n è

ultimo figlio, restituisce il simbolo speciale >attach attacca il nodo n come radice di Tbuild assume in ingresso due alberi; restituisce l’albero costruito

attaccando la radice del secondo argomento come ultimofiglio della radice del primo argomento (gli interi alberi restanoattaccati)

null prende in ingresso un valore T ∈ Tree; restituisce true se Tè l’albero vuoto; false altrimenti.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 8 / 24

Page 19: Fondamenti di Informatica (Elettronici)

Alberi n-ari

bbbbbb

DEFINIZIONE (induttiva)

Un albero T e’ un grafo in cuiEsiste un nodo r con n nodi successori(a1, . . . , an); r e’ detto radice .

Tutti i nodi di T , tranne r , possonoessere ripartiti in n insiemi disgiunti,ciascuno dei quali individua in T unalbero T1, . . . , Tn con radice ai ,rispettivamente.

Grado di un nodo e’ il numero dei suoisottoalberi immediatiLe foglie hanno grado 0

ESEMPIO

Rappresentazione grafica di un albero n-ario

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 9 / 24

Page 20: Fondamenti di Informatica (Elettronici)

Alberi n-ari

bbbbbb

DEFINIZIONE (induttiva)

Un albero T e’ un grafo in cuiEsiste un nodo r con n nodi successori(a1, . . . , an); r e’ detto radice .Tutti i nodi di T , tranne r , possonoessere ripartiti in n insiemi disgiunti,ciascuno dei quali individua in T unalbero T1, . . . , Tn con radice ai ,rispettivamente.

Grado di un nodo e’ il numero dei suoisottoalberi immediatiLe foglie hanno grado 0

ESEMPIO

Rappresentazione grafica di un albero n-ario

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 9 / 24

Page 21: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Algoritmi fondamentali

Visita in profondità(Depth First Search - DFS) in PreordineAlgoritmo Preordine(T)

if T è non vuoto:elabora root(T);for each sottoalbero Ti do

Preordine(Ti)

9 45 2 24 17 6 23 14 5 8

Visita in profondità(Depth First Search - DFS) in PostordineAlgoritmo Postordine(T)

if T è non vuoto:for each sottoalbero Ti do

Postordine(Ti)elabora root(T)

2 17 24 45 6 14 5 8 23 9

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 10 / 24

Page 22: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Algoritmi fondamentali

Visita in profondità(Depth First Search - DFS) in PreordineAlgoritmo Preordine(T)

if T è non vuoto:elabora root(T);for each sottoalbero Ti do

Preordine(Ti)

9 45 2 24 17 6 23 14 5 8

Visita in profondità(Depth First Search - DFS) in PostordineAlgoritmo Postordine(T)

if T è non vuoto:for each sottoalbero Ti do

Postordine(Ti)elabora root(T)

2 17 24 45 6 14 5 8 23 9

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 10 / 24

Page 23: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Rappresentazione con liste multiple

LISTA MULTIPLA = Lista i cui elementisono atomi oppure liste

DEFINIZIONE

Un albero n-ario puo’ essere rappresentatocon liste multiple seguendo le regoleseguenti:

un albero vuoto e’ rappresentato dallalista vuota

se l’albero e’ formato da una radice e ksottoalberi e’ rappresentato da unalista di k + 1 elementi; il primo e’ unatomo che rappresenta la radice; glialtri sono liste che rappresentanoordinatamente i sottoalberi

OGNI NODO E’ rappresentato da un lista dik + 1 nodi, se k sono gli archi uscenti

MEMORIA: Space(|N|+ |A|) = O(n)

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 11 / 24

Page 24: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Rappresentazione con liste multiple

LISTA MULTIPLA = Lista i cui elementisono atomi oppure liste

DEFINIZIONE

Un albero n-ario puo’ essere rappresentatocon liste multiple seguendo le regoleseguenti:

un albero vuoto e’ rappresentato dallalista vuotase l’albero e’ formato da una radice e ksottoalberi e’ rappresentato da unalista di k + 1 elementi; il primo e’ unatomo che rappresenta la radice; glialtri sono liste che rappresentanoordinatamente i sottoalberi

OGNI NODO E’ rappresentato da un lista dik + 1 nodi, se k sono gli archi uscenti

MEMORIA: Space(|N|+ |A|) = O(n)

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 11 / 24

Page 25: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Rappresentazione con alberi binari

RAPPRESENTAZIONE CON ALBERIBINARI

Ogni valore di tipo albero n-ario e’rappresentato da un valore di tipo alberobinario, seguendo le seguenti

REGOLE:(a) il primo figlio di un nodo viene

rappresentato dalla radice del suosottoalbero sinistro

(b) il fratello destro di un nodo vienerappresentato dalla radice del suosottoalbero destro

Rappresentazione di un albero n-ario con unalbero binario

MEMORIA: O(n)

Più efficiente che con liste !!

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 12 / 24

Page 26: Fondamenti di Informatica (Elettronici)

Alberi n-ari

Rappresentazione con alberi binari

RAPPRESENTAZIONE CON ALBERIBINARI

Ogni valore di tipo albero n-ario e’rappresentato da un valore di tipo alberobinario, seguendo le seguenti

REGOLE:(a) il primo figlio di un nodo viene

rappresentato dalla radice del suosottoalbero sinistro

(b) il fratello destro di un nodo vienerappresentato dalla radice del suosottoalbero destro

Rappresentazione di un albero n-ario con unalbero binario

MEMORIA: O(n)

Più efficiente che con liste !!

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 12 / 24

Page 27: Fondamenti di Informatica (Elettronici)

Rappresentazioni dei grafi

Section 3

Rappresentazioni dei grafi

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 13 / 24

Page 28: Fondamenti di Informatica (Elettronici)

Rappresentazioni dei grafi

Grafi orientati

xRicordiamo la definizione di grafo orientato:

Si dice grafo orientato G una coppia ordinata (N,A), dove N è un insieme finito dielementi qualsiasi, detti nodi, e A, detto insieme degli archi, è una relazione binaria su N

Un grafo non orientato G = (V, E) è costituito da un insieme V di vertici e da un insiemeE di spigoli, elementi di una relazione simmetrica (e normalmente antiriflessiva) su V

Nel seguito ci occupiamo in particolare di grafi orientati

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 14 / 24

Page 29: Fondamenti di Informatica (Elettronici)

Rappresentazioni dei grafi

Matrici di adiacenza

DEFINIZIONESi dice matrice di adiacenza(nodi/nodi) di un grafo G = (N, A)una matrice binaria B così definita:A = [0 1 1 0 0 1

0 0 0 1 0 00 0 0 0 1 00 0 0 0 0 10 1 0 1 0 10 0 0 0 0 0]

A = (bij), bij =

1 se (ni , nj) ∈ A

0 altrimenti

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 15 / 24

Page 30: Fondamenti di Informatica (Elettronici)

Rappresentazioni dei grafi

Matrici di adiacenza

• La somma degli elementi della matrice eguaglia il numero degli archi:∑i

∑j

= |A|

• La somma per righe è pari al numero di archi uscenti da un nodo:∑j

= outdegree(ni )

• La somma per colonne è pari al numero di archi entranti in un nodo:∑i

= indegree(nj)

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 16 / 24

Page 31: Fondamenti di Informatica (Elettronici)

Rappresentazioni dei grafi

Matrici di adiacenza

[0 1 1 0 0 1;0 0 0 1 0 0;0 0 0 0 1 0; +0 0 0 0 0 1;0 1 0 1 0 1;0 0 0 0 0 0]

[0 0 0 0 0 0;1 0 0 0 1 0;1 0 0 0 0 0; =0 1 0 0 1 0;0 0 1 0 0 0;1 0 0 1 1 0]

[0 1 1 0 0 1;1 0 0 1 1 0;1 0 0 0 1 0;0 1 0 0 1 1;0 1 1 1 0 1;1 0 0 1 1 0]

Data la matrice di adiacenza A di un grafo orientato (senza cappi e archi doppi), lamatrice di adiacenza B> , del corrispondente grafo non orientato sugli stessi nodi siottiene sommando B e la sua trasposta

A + A' = B

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 17 / 24

Page 32: Fondamenti di Informatica (Elettronici)

Rappresentazioni dei grafi

Matrici di incidenza

Si dice matrice di incidenza (nodi/archi) di ungrafo orientato G = (N, A) una matrice C avalori in {−1, 0, 1} così definita:

C = (cij), cij =

{ −1 se ni ∈ Aj1 se nj ∈ Ai0 altrimenti

C = [-1 0 0 -1 0 0 -1 0 01 -1 0 0 0 0 0 1 00 0 0 1 -1 0 0 0 00 1 -1 0 0 0 0 0 10 0 0 0 1 -1 0 -1 -10 0 1 0 0 1 1 0 0]

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 18 / 24

Page 33: Fondamenti di Informatica (Elettronici)

Operazioni topologiche su grafi

Section 4

Operazioni topologiche su grafi

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 19 / 24

Page 34: Fondamenti di Informatica (Elettronici)

Operazioni topologiche su grafi

bbbbbb

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 20 / 24

Page 35: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Section 5

Noteworthy differences from Python

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 21 / 24

Page 36: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 1/3https://docs.julialang.org/en/v1/manual/noteworthy-differences/

1 Julia’s for, if, while, etc. blocks are terminated by the end keyword. Indentationlevel is not significant as it is in Python. Unlike Python, Julia has no pass keyword.

2 Strings are denoted by double quotation marks (“text”) in Julia (with three doublequotation marks for multi-line strings), whereas in Python they can be denotedeither by single (‘text’) or double quotation marks (“text”). Single quotation marksare used for characters in Julia (‘c’).

3 String concatenation is done with * in Julia, not + like in Python. Analogously,string repetition is done with ˆ, not *. Implicit string concatenation of string literalslike in Python (e.g. ‘ab’ ‘cd’ == ‘abcd’) is not done in Julia.

4 Python Lists—flexible but slow—correspond to the Julia Vector{Any} type or moregenerally Vector{T} where T is some non-concrete element type. “Fast” arrays likeNumpy arrays that store elements in-place (i.e., dtype is np.float64, [(‘f1’,np.uint64), (‘f2’, np.int32)], etc.) can be represented by Array{T} where T is aconcrete, immutable element type. This includes built-in types like Float64, Int32,Int64 but also more complex types like Tuple{UInt64,Float64} and manyuser-defined types as well.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 22 / 24

Page 37: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 1/3https://docs.julialang.org/en/v1/manual/noteworthy-differences/

1 Julia’s for, if, while, etc. blocks are terminated by the end keyword. Indentationlevel is not significant as it is in Python. Unlike Python, Julia has no pass keyword.

2 Strings are denoted by double quotation marks (“text”) in Julia (with three doublequotation marks for multi-line strings), whereas in Python they can be denotedeither by single (‘text’) or double quotation marks (“text”). Single quotation marksare used for characters in Julia (‘c’).

3 String concatenation is done with * in Julia, not + like in Python. Analogously,string repetition is done with ˆ, not *. Implicit string concatenation of string literalslike in Python (e.g. ‘ab’ ‘cd’ == ‘abcd’) is not done in Julia.

4 Python Lists—flexible but slow—correspond to the Julia Vector{Any} type or moregenerally Vector{T} where T is some non-concrete element type. “Fast” arrays likeNumpy arrays that store elements in-place (i.e., dtype is np.float64, [(‘f1’,np.uint64), (‘f2’, np.int32)], etc.) can be represented by Array{T} where T is aconcrete, immutable element type. This includes built-in types like Float64, Int32,Int64 but also more complex types like Tuple{UInt64,Float64} and manyuser-defined types as well.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 22 / 24

Page 38: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 1/3https://docs.julialang.org/en/v1/manual/noteworthy-differences/

1 Julia’s for, if, while, etc. blocks are terminated by the end keyword. Indentationlevel is not significant as it is in Python. Unlike Python, Julia has no pass keyword.

2 Strings are denoted by double quotation marks (“text”) in Julia (with three doublequotation marks for multi-line strings), whereas in Python they can be denotedeither by single (‘text’) or double quotation marks (“text”). Single quotation marksare used for characters in Julia (‘c’).

3 String concatenation is done with * in Julia, not + like in Python. Analogously,string repetition is done with ˆ, not *. Implicit string concatenation of string literalslike in Python (e.g. ‘ab’ ‘cd’ == ‘abcd’) is not done in Julia.

4 Python Lists—flexible but slow—correspond to the Julia Vector{Any} type or moregenerally Vector{T} where T is some non-concrete element type. “Fast” arrays likeNumpy arrays that store elements in-place (i.e., dtype is np.float64, [(‘f1’,np.uint64), (‘f2’, np.int32)], etc.) can be represented by Array{T} where T is aconcrete, immutable element type. This includes built-in types like Float64, Int32,Int64 but also more complex types like Tuple{UInt64,Float64} and manyuser-defined types as well.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 22 / 24

Page 39: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 1/3https://docs.julialang.org/en/v1/manual/noteworthy-differences/

1 Julia’s for, if, while, etc. blocks are terminated by the end keyword. Indentationlevel is not significant as it is in Python. Unlike Python, Julia has no pass keyword.

2 Strings are denoted by double quotation marks (“text”) in Julia (with three doublequotation marks for multi-line strings), whereas in Python they can be denotedeither by single (‘text’) or double quotation marks (“text”). Single quotation marksare used for characters in Julia (‘c’).

3 String concatenation is done with * in Julia, not + like in Python. Analogously,string repetition is done with ˆ, not *. Implicit string concatenation of string literalslike in Python (e.g. ‘ab’ ‘cd’ == ‘abcd’) is not done in Julia.

4 Python Lists—flexible but slow—correspond to the Julia Vector{Any} type or moregenerally Vector{T} where T is some non-concrete element type. “Fast” arrays likeNumpy arrays that store elements in-place (i.e., dtype is np.float64, [(‘f1’,np.uint64), (‘f2’, np.int32)], etc.) can be represented by Array{T} where T is aconcrete, immutable element type. This includes built-in types like Float64, Int32,Int64 but also more complex types like Tuple{UInt64,Float64} and manyuser-defined types as well.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 22 / 24

Page 40: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 2/3

1 In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.

2 Julia’s slice indexing includes the last element, unlike in Python. a[2:3] inJulia is a[1:3] in Python.

3 Julia does not support negative indices. In particular, the last element of a listor array is indexed with end in Julia, not -1 as in Python.

4 Julia requires end for indexing until the last element. x[1:] in Python isequivalent to x[2:end] in Julia.

5 Julia’s range indexing has the format of x[start:step:stop], whereas Python’sformat is x[start:(stop+1):step]. Hence, x[0:10:2] in Python is equivalent tox[1:2:10] in Julia. Similarly, x[::-1] in Python, which refers to the reversedarray, is equivalent to x[end:-1:1] in Julia.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 23 / 24

Page 41: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 2/3

1 In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.2 Julia’s slice indexing includes the last element, unlike in Python. a[2:3] in

Julia is a[1:3] in Python.

3 Julia does not support negative indices. In particular, the last element of a listor array is indexed with end in Julia, not -1 as in Python.

4 Julia requires end for indexing until the last element. x[1:] in Python isequivalent to x[2:end] in Julia.

5 Julia’s range indexing has the format of x[start:step:stop], whereas Python’sformat is x[start:(stop+1):step]. Hence, x[0:10:2] in Python is equivalent tox[1:2:10] in Julia. Similarly, x[::-1] in Python, which refers to the reversedarray, is equivalent to x[end:-1:1] in Julia.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 23 / 24

Page 42: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 2/3

1 In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.2 Julia’s slice indexing includes the last element, unlike in Python. a[2:3] in

Julia is a[1:3] in Python.3 Julia does not support negative indices. In particular, the last element of a list

or array is indexed with end in Julia, not -1 as in Python.

4 Julia requires end for indexing until the last element. x[1:] in Python isequivalent to x[2:end] in Julia.

5 Julia’s range indexing has the format of x[start:step:stop], whereas Python’sformat is x[start:(stop+1):step]. Hence, x[0:10:2] in Python is equivalent tox[1:2:10] in Julia. Similarly, x[::-1] in Python, which refers to the reversedarray, is equivalent to x[end:-1:1] in Julia.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 23 / 24

Page 43: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 2/3

1 In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.2 Julia’s slice indexing includes the last element, unlike in Python. a[2:3] in

Julia is a[1:3] in Python.3 Julia does not support negative indices. In particular, the last element of a list

or array is indexed with end in Julia, not -1 as in Python.4 Julia requires end for indexing until the last element. x[1:] in Python is

equivalent to x[2:end] in Julia.

5 Julia’s range indexing has the format of x[start:step:stop], whereas Python’sformat is x[start:(stop+1):step]. Hence, x[0:10:2] in Python is equivalent tox[1:2:10] in Julia. Similarly, x[::-1] in Python, which refers to the reversedarray, is equivalent to x[end:-1:1] in Julia.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 23 / 24

Page 44: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 2/3

1 In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.2 Julia’s slice indexing includes the last element, unlike in Python. a[2:3] in

Julia is a[1:3] in Python.3 Julia does not support negative indices. In particular, the last element of a list

or array is indexed with end in Julia, not -1 as in Python.4 Julia requires end for indexing until the last element. x[1:] in Python is

equivalent to x[2:end] in Julia.5 Julia’s range indexing has the format of x[start:step:stop], whereas Python’s

format is x[start:(stop+1):step]. Hence, x[0:10:2] in Python is equivalent tox[1:2:10] in Julia. Similarly, x[::-1] in Python, which refers to the reversedarray, is equivalent to x[end:-1:1] in Julia.

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 23 / 24

Page 45: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 3/3

1 In Julia, indexing a matrix with arrays like X[[1,2], [1,3]] refers to a sub-matrix thatcontains the intersections of the first and second rows with the first and thirdcolumns. In Python, X[[1,2], [1,3]] refers to a vector that contains the values of cell[1,1] and [2,3] in the matrix. X[[1,2], [1,3]] in Julia is equivalent withX[np.ix_([0,1],[0,2])] in Python. X[[0,1], [0,2]] in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]] in Julia.

2 Julia has no line continuation syntax: if, at the end of a line, the input so far is acomplete expression, it is considered done; otherwise the input continues. One wayto force an expression to continue is to wrap it in parentheses.

3 Julia arrays are column major (Fortran ordered) whereas NumPy arrays are rowmajor (C-ordered) by default. To get optimal performance when looping over arrays,the order of the loops should be reversed in Julia relative to NumPy (see relevantsection of Performance Tips).

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 24 / 24

Page 46: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 3/3

1 In Julia, indexing a matrix with arrays like X[[1,2], [1,3]] refers to a sub-matrix thatcontains the intersections of the first and second rows with the first and thirdcolumns. In Python, X[[1,2], [1,3]] refers to a vector that contains the values of cell[1,1] and [2,3] in the matrix. X[[1,2], [1,3]] in Julia is equivalent withX[np.ix_([0,1],[0,2])] in Python. X[[0,1], [0,2]] in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]] in Julia.

2 Julia has no line continuation syntax: if, at the end of a line, the input so far is acomplete expression, it is considered done; otherwise the input continues. One wayto force an expression to continue is to wrap it in parentheses.

3 Julia arrays are column major (Fortran ordered) whereas NumPy arrays are rowmajor (C-ordered) by default. To get optimal performance when looping over arrays,the order of the loops should be reversed in Julia relative to NumPy (see relevantsection of Performance Tips).

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 24 / 24

Page 47: Fondamenti di Informatica (Elettronici)

Noteworthy differences from Python

Noteworthy differences from Python 3/3

1 In Julia, indexing a matrix with arrays like X[[1,2], [1,3]] refers to a sub-matrix thatcontains the intersections of the first and second rows with the first and thirdcolumns. In Python, X[[1,2], [1,3]] refers to a vector that contains the values of cell[1,1] and [2,3] in the matrix. X[[1,2], [1,3]] in Julia is equivalent withX[np.ix_([0,1],[0,2])] in Python. X[[0,1], [0,2]] in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]] in Julia.

2 Julia has no line continuation syntax: if, at the end of a line, the input so far is acomplete expression, it is considered done; otherwise the input continues. One wayto force an expression to continue is to wrap it in parentheses.

3 Julia arrays are column major (Fortran ordered) whereas NumPy arrays are rowmajor (C-ordered) by default. To get optimal performance when looping over arrays,the order of the loops should be reversed in Julia relative to NumPy (see relevantsection of Performance Tips).

n-alberi e grafi – Lezione 39 Fondamenti di Informatica (Elettronici) 20 gennaio 2021 24 / 24