Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Joaquim Gabarro
gabarro@cs.upc.edu
Computer Science
Universitat Politècnica de Catalunya
Copias Frescas
Ordenación (Sorting)
Ejemplo:
>>> L=[1,2,3]
>>> M=copy(L)
>>> M
[1, 2, 3]
>>> M[0]=5
>>> M
[5, 2, 3]
>>> L
[1, 2, 3]
Copia (II)
Utilizar el extend:
>>> L=[1,2,3]
>>> M=[]
>>> M.extend(L)
>>> M
[1, 2, 3]
>>> M[0]=5
>>> M
[5, 2, 3]
>>> L
[1, 2, 3]
Ordenación (Sorting)
Build-in functions
https://docs.python.org/3/howto/sorting.html
For a simple ascending sort call sorted(). It returns a new
sorted list
>>> L= sorted([5, 2, 3, 1, 4])
>>> L
[1, 2, 3, 4, 5]
Tenemos:
def insertion_sort(L):
for i in range(1,len(L)):
x = L[i]
insertar x en la posicion adecuada en L[:i-1]
se traduce en
a la lista:
def insertion_sort(L):
for i in range(1,len(L)):
x = L[i]
j = i
while j>0 and L[j-1]>x:
L[j], j = L[j-1], j-1
L[j]=x
>>> L = [54,26,93,17,77,31,44,55,20]
>>> print(L)
[54, 26, 93, 17, 77, 31, 44, 55, 20]
>>> M= insertion_sort(L)
>>> print(M)
None
>>>
>>> print(L)
[17, 20, 26, 31, 44, 54, 55, 77, 93]
No tocar L
Copiamos L en M y ordenamos M con insertion sort.py.
Fichero other insertion sort.py
def insertion_sort(L):
...
def other_insertion_sort(L):
M=[i for i in L]
insertion_sort(M)
return M
Ejemplo:
>>> L = [54,26,93,17,77,31,44,55,20]
>>> L1=other_insertion_sort(L)
>>> L1
[17, 20, 26, 31, 44, 54, 55, 77, 93]
>>> L
[54, 26, 93, 17, 77, 31, 44, 55, 20]
>>>
Operaciones con matrices
Ejemplo: Producto de Matrices
Por ejemplo:
1
c1,2 = 3 1 0 ∗ 1 =3∗1+1∗1+0∗0=4
0
Solución (I)
Aplicando las ideas de mas uno.py de la clase anterior
obtenemos mat mult.py
def mat_mult(A,B):
p,q,r = len(A), len(A[0]), len(B[0])
C=[]
for i in range(p):
fila=[]
for j in range(r):
s=0
for k in range(q):
s=s+A[i][k]*B[k][j]
fila.append(s)
C.append(fila)
return C
Solución (II)
Ejemplo:
1 4
1 2 3
M= , MT = 2 5
4 5 6
3 6
Solucion (I)
def transpose(M):
p,q = len(M), len(M[0])
T=[[M[j][i] for j in range(p)] for i in range(q)]
return T
Apéndice: Merge Sort
merge sort(L)
[17,20,26,31,44,54,55,77,93]
Fichero merge sort.py
def merge_sort(L):
print("split", L)
if len(L)>1:
mid = len(L)//2
left,right = L[:mid],L[mid:]
merge_sort(left)
merge_sort(right)
merge (left, right, L)
print("merge", L)
Ejecutando:
def main():
L = [54,26,93,17,77,31,44,55,20]
print(L)
merge_sort(L)
print(L)