TallerPython
TallerPython
Este PDF puede estar desactualizado. El notebook al día puede ser visto acá:
https://github.com/algoritmos-rw/algo2_apuntes/blob/master/TallerPython.ipynb
1 Un poco de Historia
• Python fue creado a finales de los años 80 por un programador holandés llamado Guido
van Rossum, quien sigue siendo aún hoy el líder del desarrollo del lenguaje.
"I chose Python as a working title for the project, being in a slightly irreverent mood (and a big
fan of Monty Python’s Flying Circus)."
3 La filosofía de Python
In [3]: import this
1
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Hello World!
Hola
1
1.0
(1, 1.0)
(1, 1.0, 'Hola')
[1, 1.0, 'Hola']
{'1': (1, 1.0), 50: (1, 1.0, 'Hola'), '3': 1}
{1, 2}
2
print(elemento)
print(type(elemento))
elemento = "uno"
print(elemento)
print(type(elemento))
1
<class 'int'>
uno
<class 'str'>
5 Funciones en Python
In [7]: # Definir una función
def suma(a,b):
return a+b
print(suma(1,2))
print(suma(1.0,2.0))
print(suma(1.0,2))
print(suma("hola ","como te va"))
print(suma([1,2,3],[4,5]))
print(suma("1",3)) # Falla
3
3.0
3.0
hola como te va
[1, 2, 3, 4, 5]
---------------------------------------------------------------------------
<ipython-input-7-193b5862090a> in <module>()
8 print(suma("hola ","como te va"))
9 print(suma([1,2,3],[4,5]))
---> 10 print(suma("1",3)) # Falla
<ipython-input-7-193b5862090a> in suma(a, b)
1 # Definir una función
2 def suma(a,b):
----> 3 return a+b
4
3
5 print(suma(1,2))
4.0
0.5
0.5
0.5
7 Listas de Python
In [9]: # Como hacer una lista
lista = [] # A modo de ejemplo llamamos a la lista "lista", pero no deben llamar a las
4
---------------------------------------------------------------------------
<ipython-input-9-98399ff64c8a> in <module>()
11 print(lista[2]) # Imprimo elemento en la posición 2
12 print(lista[-1]) # Imprimo elemento en la última posición
---> 13 print(lista[10]) # Falla
print("Segunda iteración")
for i, elemento in enumerate(lista):
print("\tIndice:",i)
print("\tValor:",elemento)
Primera iteración
1
5
dos
10
3.0
Segunda iteración
Indice: 0
Valor: 1
Indice: 1
Valor: dos
Indice: 2
Valor: 10
Indice: 3
Valor: 3.0
Tercera iteración
1
dos
Cuarta iteración
1
dos
10
3.0
['dos', 10, 3.0]
10
['dos', 3.0]
8 Condicionales (if...elif...else)
if <condición_1>:
<hacer algo_1 si se da la condición_1>
elif <condición_2>:
<hacer algo_2 si se da la condición_2>
...
elif <condición_n>:
<hacer algo_n si se da la condición_n>
else:
<hacer otra cosa si no dan las anteriores>
6
if lista[mitad]<elemento:
return busqueda_binaria(lista[mitad:],elemento)
print(busqueda_binaria([1,2,3,4,5],4))
print(busqueda_binaria([1,4,6,7,9,10],2))
True
False
9 Slices
Valen para listas, tuplas o strings (segmentos)
numeros = numeros[::-1]
print(numeros)
[1, 2]
[7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3]
[4, 5, 6, 7, 8, 9, 10]
[1, 3, 5, 7, 9]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
10 Diccionarios de Python
Son como hashmaps, las claves deben ser inmutables para que no pierda sentido el diccionario. Si
se pudieran modificar, se podría cambiar las claves y podría generar conflictos.
Tipos mutables: - Listas - Diccionarios - Sets
Tipos inmutables: - Int - Float - String - Tuplas
Out[13]: 'H'
7
# Cómo agregar cosas al diccionario
diccionario['clave1'] = 'valor1'
diccionario[2] = 'valor2'
diccionario['clave3'] = 3
print(diccionario)
# [('clave1','valor1'),('clave2','valor2'),('clave3',3)]
print(diccionario.get('clave3',2)) # Equivalente a diccionario['clave3']
# pero en caso de no tener la clave, devuelve
# un elemento por default (en este caso 2)
8
11 Sets
Son similares a los diccionarios pero se almacenan solo claves, y tienen algunas operaciones par-
ticulares.
In [15]: help("set")
class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
|
| __contains__(...)
| x.__contains__(y) <==> y in x.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __gt__(self, value, /)
| Return self>value.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __isub__(self, value, /)
| Return self-=value.
|
| __iter__(self, /)
9
| Implement iter(self).
|
| __ixor__(self, value, /)
| Return selfˆ=value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __reduce__(...)
| Return state information for pickling.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rxor__(self, value, /)
| Return valueˆself.
|
| __sizeof__(...)
| S.__sizeof__() -> size of S in memory, in bytes
|
| __sub__(self, value, /)
| Return self-value.
|
| __xor__(self, value, /)
10
| Return selfˆvalue.
|
| add(...)
| Add an element to a set.
|
| This has no effect if the element is already present.
|
| clear(...)
| Remove all elements from this set.
|
| copy(...)
| Return a shallow copy of a set.
|
| difference(...)
| Return the difference of two or more sets as a new set.
|
| (i.e. all elements that are in this set but not the others.)
|
| difference_update(...)
| Remove all elements of another set from this set.
|
| discard(...)
| Remove an element from a set if it is a member.
|
| If the element is not a member, do nothing.
|
| intersection(...)
| Return the intersection of two sets as a new set.
|
| (i.e. all elements that are in both sets.)
|
| intersection_update(...)
| Update a set with the intersection of itself and another.
|
| isdisjoint(...)
| Return True if two sets have a null intersection.
|
| issubset(...)
| Report whether another set contains this set.
|
| issuperset(...)
| Report whether this set contains another set.
|
| pop(...)
| Remove and return an arbitrary set element.
| Raises KeyError if the set is empty.
|
| remove(...)
11
| Remove an element from a set; it must be a member.
|
| If the element is not a member, raise a KeyError.
|
| symmetric_difference(...)
| Return the symmetric difference of two sets as a new set.
|
| (i.e. all elements that are in exactly one of the sets.)
|
| symmetric_difference_update(...)
| Update a set with the symmetric difference of itself and another.
|
| union(...)
| Return the union of sets as a new set.
|
| (i.e. all elements that are in either set.)
|
| update(...)
| Update a set with the union of itself and others.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
12
Alumno, nota
0,8
1,9
2,0
3,4
4,2
5,6
6,6
7,3
8,9
9,6
13 Archivos CSV
In [18]: import csv
with open('archivo.csv','r') as f:
f_reader = csv.DictReader(f,delimiter=',')
#f_reader = csv.reader(f,delimiter = ',') # Devuelve lista de elementos
for row in f_reader:
print(row)
13
f_writer.writerow([1,2])
f_writer.writerow([2,3])
f_writer.writerow([4,5])
14 Split y Join
• Split: opera sobre un string, recibe un delimitador, y devuelve una lista de fragmentos del
string delimitados por el delimitador.
• Join: opera sobre un string (delimitador), recibe una lista de strings, y devuelve un string de
los fragmentos unidos por el delimitador.
15 Objetos
Los objetos tiene metodos y atributos: - Atributos: equivalentes a variables. - Métodos: equiva-
lentes a las funciones.
Se puede trazar una equivalencia entre los objetos y los structs de C, "ambas son estructuras
en las que se le pueden guardar cosas".
La clase de un objeto es el tipo.
Por ejemplo:
En C, para definir un nodo haciamos:
def obtener_dato(self):
return self.dato;
def proximo(self):
14
return self.siguiente
def __repr__(self):
return str(self.dato)
def __str__(self):
return str(self.dato)
hola
[hola, lala]
hola
def __init__(self):
self.primero = None
self.ultimo = None
self.largo = 0
def insertar_al_principio(self,dato):
nodo = Nodo(dato, self.primero)
self.primero = nodo
self.largo += 1
if self.largo == 1:
self.ultimo = nodo
def insertar_al_final(self,dato):
if self.largo != 0:
nodo = Nodo(dato)
nodo_anterior = self.ultimo
nodo_anterior.siguiente = nodo
self.ultimo = nodo
self.largo += 1
else:
self.insertar_al_principio(dato)
def ver_primero(self):
return self.primero.obtener_dato();
15
def borrar_primero(self):
dato = self.primero.obtener_dato()
self.primero = self.primero.siguiente
self.largo -= 1
if self.largo == 0:
self.ultimo = None
return dato
def __str__(self):
cadena = ""
nodo_actual = self.primero
while nodo_actual is not None:
cadena += str(nodo_actual.obtener_dato())
cadena += " | "
nodo_actual = nodo_actual.siguiente
return cadena
lista = Lista_Enlazada()
lista.insertar_al_principio("Primer Dato")
lista.insertar_al_principio("Primer primer Dato")
elemento = lista.ver_primero()
print(elemento)
print(str(lista))
heap = [5,2,3,7,2,20,1]
heapq.heapify(heap)
print(heap)
heapq.heappush(heap,27)
print(heap)
menor = heapq.heappop(heap)
print(menor)
print(heap)
n_menores = heapq.nsmallest(3,heap)
print(n_menores)
16
[1, 2, 3, 7, 2, 20, 5]
[1, 2, 3, 7, 2, 20, 5, 27]
1
[2, 2, 3, 7, 27, 20, 5]
[2, 2, 3]
def obtener_valor():
return dato
def __str__(self):
return str(self.dato)
def __repr__(self):
return str(self.dato)
[20, 7, 5, 2, 2, 3, 1]
17
Problema: En el primer caso encolar y en el segundo caso desencolar del principio implica
desplazar todo el contenido de la lista (en un sentido u otro). Esta operación es costosa, imaginense
una lista muy grande!
19.3 Recursos
• Apunte de Algoritmos y Programación I
• Curso Python
• Python Tutor
18