Commit 6991deac authored by Alejandro Molina Villegas's avatar Alejandro Molina Villegas

numpy clase

parents b91912e7 2434cc60
......@@ -24,7 +24,9 @@
"* Interpretado (Se ejecuta sin compilación previa)\n",
"* Tipificación Dinamica (Se realiza durante en tiempo de ejecución)\n",
"* Multiparadigma\n",
"* Interactivo (con ipython)\n"
"* Interactivo (con ipython)\n",
"\n",
"*Nota: Python obtiene su nombre del programa de la BBC [Monty Python's Flying Circus](https://www.imdb.com/title/tt0063929/).*"
]
},
{
......@@ -40,7 +42,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 1,
"metadata": {},
"outputs": [
{
......@@ -49,7 +51,7 @@
"int"
]
},
"execution_count": 5,
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
......@@ -60,7 +62,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 2,
"metadata": {},
"outputs": [
{
......@@ -69,7 +71,7 @@
"float"
]
},
"execution_count": 6,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
......@@ -80,7 +82,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 3,
"metadata": {},
"outputs": [
{
......@@ -89,7 +91,7 @@
"complex"
]
},
"execution_count": 7,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
......@@ -110,7 +112,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 4,
"metadata": {},
"outputs": [
{
......@@ -119,7 +121,7 @@
"list"
]
},
"execution_count": 9,
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
......@@ -130,7 +132,7 @@
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 5,
"metadata": {},
"outputs": [
{
......@@ -139,7 +141,7 @@
"tuple"
]
},
"execution_count": 10,
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
......@@ -150,7 +152,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 6,
"metadata": {},
"outputs": [
{
......@@ -159,13 +161,13 @@
"range"
]
},
"execution_count": 11,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
" type(range(1))"
"type(range(1))"
]
},
{
......@@ -178,7 +180,7 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 7,
"metadata": {},
"outputs": [
{
......@@ -187,7 +189,7 @@
"str"
]
},
"execution_count": 13,
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
......@@ -206,7 +208,7 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 8,
"metadata": {},
"outputs": [
{
......@@ -215,7 +217,7 @@
"dict"
]
},
"execution_count": 15,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
......@@ -235,7 +237,7 @@
},
{
"cell_type": "code",
"execution_count": 34,
"execution_count": 9,
"metadata": {},
"outputs": [
{
......@@ -244,7 +246,7 @@
"{1, 2, 3, 5, 6}"
]
},
"execution_count": 34,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
......@@ -273,7 +275,7 @@
},
{
"cell_type": "code",
"execution_count": 16,
"execution_count": 10,
"metadata": {},
"outputs": [
{
......@@ -282,7 +284,7 @@
"True"
]
},
"execution_count": 16,
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
......@@ -293,7 +295,7 @@
},
{
"cell_type": "code",
"execution_count": 18,
"execution_count": 11,
"metadata": {},
"outputs": [
{
......@@ -302,7 +304,7 @@
"False"
]
},
"execution_count": 18,
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
......@@ -313,7 +315,7 @@
},
{
"cell_type": "code",
"execution_count": 19,
"execution_count": 12,
"metadata": {},
"outputs": [
{
......@@ -322,7 +324,7 @@
"False"
]
},
"execution_count": 19,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
......@@ -333,7 +335,7 @@
},
{
"cell_type": "code",
"execution_count": 17,
"execution_count": 13,
"metadata": {},
"outputs": [
{
......@@ -342,7 +344,7 @@
"True"
]
},
"execution_count": 17,
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
......@@ -353,7 +355,7 @@
},
{
"cell_type": "code",
"execution_count": 22,
"execution_count": 14,
"metadata": {},
"outputs": [
{
......@@ -362,7 +364,7 @@
"False"
]
},
"execution_count": 22,
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
......@@ -373,7 +375,7 @@
},
{
"cell_type": "code",
"execution_count": 23,
"execution_count": 15,
"metadata": {},
"outputs": [
{
......@@ -382,7 +384,7 @@
"True"
]
},
"execution_count": 23,
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
......@@ -437,7 +439,7 @@
},
{
"cell_type": "code",
"execution_count": 36,
"execution_count": 16,
"metadata": {},
"outputs": [
{
......@@ -457,7 +459,7 @@
},
{
"cell_type": "code",
"execution_count": 38,
"execution_count": 17,
"metadata": {},
"outputs": [
{
......@@ -479,7 +481,7 @@
},
{
"cell_type": "code",
"execution_count": 42,
"execution_count": 18,
"metadata": {},
"outputs": [
{
......@@ -499,7 +501,7 @@
},
{
"cell_type": "code",
"execution_count": 44,
"execution_count": 19,
"metadata": {},
"outputs": [
{
......@@ -521,6 +523,99 @@
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"3\n",
"4\n"
]
}
],
"source": [
"for i in range(5):\n",
" if(i==2):\n",
" continue\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n"
]
}
],
"source": [
"for i in range(5):\n",
" if(i==2):\n",
" break\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n"
]
}
],
"source": [
"for i in range(5):\n",
" if(i==2):\n",
" pass\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5\n",
"0.6666666666666666\n",
"1.0\n",
"2.0\n",
"ERROR\n"
]
}
],
"source": [
"for i in reversed(range(5)):\n",
" try:\n",
" print(2/i)\n",
" except:\n",
" print(\"ERROR\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -535,8 +630,148 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1.4 Ejercicios\n",
"## 1.4.1 Inprimir todos los numeros pares en 0 y 20."
"## 1.4 Funciones\n",
"Una función es un conjunto de setencias que pueden ser invocadas varias veces durante la ejecución de un programa. Permiten minimizar el codigo, amuentar su legibilidad y permiten reutilizar código. En python las funciones son definida por la palabra reservada **def**. \n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello World\n"
]
}
],
"source": [
"def HelloWorld():\n",
" print(\"Hello World\")\n",
"\n",
"HelloWorld()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.1 Parametros\n",
"La funciones pueden aceptar arguentos de entrada y devoler resultados."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Mario\n"
]
}
],
"source": [
"def Hello(name):\n",
" print(\"Hello \"+name)\n",
"Hello(\"Mario\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.2 Parametros Opcionales\n",
"Las funciones tampien pueden aceptar parametros opcionales, los cuales toman en valor indicado por defecto si no son pasados a la funcion."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Mario!!!\n",
"Hello Mario?\n",
"Hello Mario!\n",
"Hello Alex!!\n"
]
},
{
"data": {
"text/plain": [
"[1]"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def Hello(name, x=\"!!!\"):\n",
" print(\"Hello \" + name + x)\n",
"Hello(\"Mario\")\n",
"Hello(\"Mario\",\"?\")\n",
"Hello(x=\"!\", name=\"Mario\")\n",
"p = {\"name\":\"Alex\", \"x\":\"!!\"}\n",
"Hello(**p)\n",
"[1,]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.3 Desempaquetado"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 1 2\n",
"0 4 5\n",
"[6, 7, 8] 1 2\n",
"6 7 8\n",
"{'a': 9, 'b': 10, 'c': 11} 1 2\n",
"9 10 11\n"
]
}
],
"source": [
"def unpack(a,b=1,c=2):\n",
" print(a,b,c)\n",
"\n",
"l = [6,7,8] \n",
"d = {\"a\":9,\"b\":10,\"c\":11} \n",
"unpack(0)\n",
"unpack(0, 4, 5)\n",
"unpack(l)\n",
"unpack(*l)\n",
"unpack(d)\n",
"unpack(**d)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.5 Ejercicios\n",
"### 1.5.1 Imprimir todos los numeros pares entre 0 y 20 usando *for* o *while*."
]
},
{
......@@ -550,12 +785,12 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.4.2 Inprimir todos los numeros myores a 10 de la lista A"
"### 1.5.2 Imprimir todos los numeros mayores a 10 de la lista A"
]
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
......@@ -567,31 +802,106 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.4.3 Dadas dos listas A y B, obten una lista con los elementos comunes a las dos listas (A∩B)."
"### 1.5.3 Dadas dos listas A y B, obten una lista con sus elementos comunes (A∩B)."
]
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n",
"b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.4 Pregunta al usario cuantos numeros de la secuancia Fibonacci quiere calcular y escribe una funcion que calcule la secuencia e imprima el resultado."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"def fibonacci(n):\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.5 Escribe una funcion que sume todos los numeros en una lista usando for."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"a = [8, 2, 3, 0, 7]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.6 Escribe una funcion que tome una lista y regrese los elementos unicos en la lista.\n"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"a = [1,2,2,3,3,3,3,4,5,5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.7 Escribe una funcion que indique si un numero es o no perfecto.\n",
"[Wikipedia:](https://es.wikipedia.org/wiki/N%C3%BAmero_perfecto) *Un número perfecto es un número natural que es igual a la suma de sus divisores propios positivos. Dicho de otra forma, un número perfecto es aquel que es amigo de sí mismo.\n",
"Así, 6 es un número perfecto porque sus divisores propios son 1, 2 y 3; y 6 = 1 + 2 + 3. Los siguientes números perfectos son 28, 496 y 8128.*\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'raw_input' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-8-504d5d148c52>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnum\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mraw_input\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Choose a number: \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mNameError\u001b[0m: name 'raw_input' is not defined"
"name": "stdout",
"output_type": "stream",
"text": [
"Escribe un nuemero:8\n"
]
}
],
"source": [
"num = int(raw_input(\"Choose a number: \"))\n",
"\n",
"\n",
"\n"
"def perfect(x):\n",
" pass\n",
"numero = input(\"Escribe un nuemero:\")\n",
"perfect(numero)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.8 Escribe una funcion que imprima las prieras *n* filas del triangulo de Pascal.\n",
"[Wolfram](http://mathworld.wolfram.com/PascalsTriangle.html):\n",
"El triángulo de Pascal es un triángulo numérico con números dispuestos en filas escalonadas de manera tal que:\n",
"$a_{nr}=\\frac{n!}{r!(n-r)!}=\\binom{n}{r}$\n"
]
},
{
......@@ -600,8 +910,42 @@
"metadata": {},
"outputs": [],
"source": [
"x = input('What is your name?: ')\n",
"\n"
"def pascal(n):\n",
" pass\n",
"numero = input(\"Indica el numero de filas:\")\n",
"pascal(numero)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.9 Escribe una funcion que indique si una frase es un panagrama.\n",
"[Wikipedia](https://es.wikipedia.org/wiki/Pangrama):Un pangrama (del griego: παν γραμμα, «todas las letras») o frase holoalfabética es un texto que usa todas las letras posibles del alfabeto de un idioma. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.10 Escribe un programa que imprima el siguiente un **for** anidado.\n",
"1\n",
"\n",
"22\n",
"\n",
"333\n",
"\n",
"4444\n",
"\n",
"55555\n",
"\n",
"666666\n",
"\n",
"7777777\n",
"\n",
"88888888\n",
"\n",
"999999999"
]
},
{
......
......@@ -241,7 +241,7 @@
},
{
"cell_type": "code",
"execution_count": 55,
"execution_count": 2,
"metadata": {},
"outputs": [
{
......@@ -297,6 +297,38 @@
"print(list(doublesG))"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Cuatos Fibonacci?: 6\n",
"0\n",
"1\n",
"1\n",
"2\n",
"3\n",
"5\n"
]
}
],
"source": [
"a = int(input('Cuatos Fibonacci?: '))\n",
"\n",
"def fib(n):\n",
" a, b = 0, 1\n",
" for _ in range(n):\n",
" yield a\n",
" a, b = b, a + b\n",
"\n",
"for n in fib(a):\n",
" print(n)"
]
},
{
"cell_type": "markdown",
"metadata": {},
......
......@@ -12,14 +12,14 @@
},
{
"cell_type": "code",
"execution_count": 28,
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" tricks = [] # Variable de clase\n",
" kind = 'canine' # Variable de clase\n",
" def __init__(self, name):\n",
" kind = 'Canis Lopus' # Variable de clase\n",
" def __init__(self, name): # Constructor de clase\n",
" self.name = name # Variable de instancia\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)"
......@@ -27,16 +27,16 @@
},
{
"cell_type": "code",
"execution_count": 29,
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 29,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
......@@ -47,7 +47,7 @@
},
{
"cell_type": "code",
"execution_count": 30,
"execution_count": 7,
"metadata": {},
"outputs": [
{
......@@ -57,7 +57,7 @@
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-30-629675d46941>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-7-629675d46941>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute 'name'"
]
}
......@@ -68,7 +68,7 @@
},
{
"cell_type": "code",
"execution_count": 31,
"execution_count": 8,
"metadata": {},
"outputs": [
{
......@@ -77,7 +77,7 @@
"'Max'"
]
},
"execution_count": 31,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
......@@ -88,7 +88,7 @@
},
{
"cell_type": "code",
"execution_count": 33,
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
......@@ -98,16 +98,16 @@
},
{
"cell_type": "code",
"execution_count": 34,
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 34,
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
......@@ -118,16 +118,16 @@
},
{
"cell_type": "code",
"execution_count": 36,
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 36,
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
......@@ -139,45 +139,404 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['roll over', 'play dead']"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Max.add_trick('roll over')\n",
"Max.add_trick('play dead')\n",
"Keeper.tricks\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"Max. def add_trick(self, trick):\n",
" self.tricks.append(trick)"
"class Dog:\n",
" __kind = 'Canis Lopus' # Variable de clase Privada\n",
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" self.tricks = [] # Variable de instancia\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" def get_kind(self):\n",
" return self.__kind"
]
},
{
"cell_type": "markdown",
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "type object 'Dog' has no attribute '__kind'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-14-4cb7b0dc9a4d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__kind\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute '__kind'"
]
}
],
"source": [
"Dog.__kind"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Canis Lopus'"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"## 3.2 Herencia"
"Max = Dog(\"Max\")\n",
"Max.get_kind()\n",
"Max._Dog__kind"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.3 Polimorfismo"
"Notas:\n",
"* **Self** no es una palabra reservada en Python solo una convencion.\n",
"* [\"why explicit self has to stay\", por Guido van Rossum](http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html)\n",
"* [We are all consenting adults](https://python-guide-chinese.readthedocs.io/zh_CN/latest/writing/style.html#we-are-all-consenting-adults) Python permite muchos trucos, y algunos de ellos son potencialmente peligrosos. Un buen ejemplo es que cualquier código de cliente puede anular las propiedades y los métodos de un objeto: no hay una palabra clave \"privada\" en Python. Esta filosofía, muy diferente de los lenguajes altamente defensivos como Java, que ofrecen muchos mecanismos para evitar cualquier uso indebido, se expresa con el dicho: \"Todos somos adultos\".\n",
"\n",
"## 3.3 Decoradores \n",
"Los decoradores son una conveniencia sintáctica, que permite que un archivo fuente de Python diga qué va a hacer con el resultado de una función o una declaración de clase antes de la declaración.\n",
"\n",
"### 3.3.1 Metodos Estaticos\n",
"**@staticmethod**\n",
"Los metodos estaticos no requieren que exista una instancia de la clase y no conocen nada sobre la clase solo sus parametros de entrada.\n",
"\n",
"\n",
"### 3.3.2 Metodos de Clase\n",
"**@classmethod** Los metodos de clase no requiren que exista a una instancia de la clase y tiene acceso a las variables de clase y solo toman como entrada un unico parametro.\n",
"\n",
"### 3.3.3 Set y Get no so Pythonicos\n",
"**@property** y **@*PROPIEDAD*.setter**, permiten acceder y modificar miembros de foma Pythonica.\n",
"\n",
"### 3.3.2 Destructor\n",
"En Python, los destructores no son tan necesarios como en C ++ porque Python tiene un recolector de basura que maneja la administración de la memoria automáticamente.\n",
"El método **__del __ ()** es el método conocido como destructor en Python. Se llama cuando todas las referencias al objeto se han eliminado, es decir, cuando un objeto se recolecta como basura."
]
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" __kind = 'Canis Lopus' # Variable privada de clase, para evitar que se modifique\n",
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" self.tricks = [] # Variable de instancia, para tenenr trucos diferentes por instancia\n",
" self.__age = 0\n",
" @property\n",
" def age(self):\n",
" return self.__age\n",
" @age.setter\n",
" def age(self, age):\n",
" self.__age = age\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" @classmethod\n",
" def get_kind(cls):\n",
" return cls.__kind\n",
" @staticmethod\n",
" def bark(times):\n",
" print(\"Guau \"*times)\n",
" def __str__(self):\n",
" return self.name + \" es un \" + self.__kind\n",
" def __del__(self): \n",
" print(self.name + \" a muerto\") "
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'dict_items' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-12-afcb87a7ff57>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mhelp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdict_items\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'dict_items' is not defined"
"name": "stdout",
"output_type": "stream",
"text": [
"Guau Guau Guau \n"
]
}
],
"source": [
"Dog.bark(3)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Canis Lopus'"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Dog.get_kind()"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"Max = Dog(\"Max\")\n",
"Max.age+=1\n",
"print(Max.age)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.4 Herencia"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Malinois(Dog):\n",
" origin = \"Bélgica\"\n",
" def fetch(self):\n",
" print(\"Fetch\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Max = Malinois(\"Max\")\n",
"print(max.get_kind())\n",
"print(max.name)\n",
"print(max.tricks)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Malinois(Dog):\n",
" __breed = \"Malinois\"\n",
" origin = \"Bélgica\"\n",
" def __init__(self, name):\n",
" super().__init__(name) #Dog.__int__(self,name)\n",
" self.tricks = [\"Fetch\"] # Variable de instancia\n",
" def fetch(self):\n",
" print(\"fetch\")\n",
" def __str__(self): #Overriding\n",
" # Obteniendo variable privada de la clase Padre\n",
" return self.name + \" es un \" + self._Dog__kind + \" de raza \" + self.__breed"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"keeper = Malinois(\"Keeper\")\n",
"print(keeper.get_kind())\n",
"print(keeper.name)\n",
"print(keeper.tricks)\n",
"print(keeper)\n",
"del(keeper)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Police:\n",
" uniform = \"Azul\"\n",
" def __init__(self, section):\n",
" self.section=section\n",
" def get_section(self):\n",
" return self.section\n",
" def __del__(self): \n",
" print(\"Dia de Jubilacion\") \n",
" \n",
"# Herencia Multiple\n",
"class Malinois(Dog, Police):\n",
" __breed = \"Malinois\"\n",
" origin = \"Bélgica\"\n",
" def __init__(self, name):\n",
" #Dog.__init__(self, name) # No usar en herencia multiple\n",
" #super(__Dog__,self).__init__(name)\n",
" #Police.__init__(self,\"K9\")\n",
" #super(__Police__,self).__init__(\"K9\")\n",
" self.tricks = [\"fetch\"] # Variable de instancia\n",
" def fetch(self):\n",
" print(\"fetch\")\n",
" def __str__(self): #Overriding\n",
" # Obteniendo variable privada de la clasfridae Padre\n",
" return self.name + \" es un \" + self._Dog__kind + \" Policia de raza \" + self.__breed + \" con uniforme \" + self.uniform\n",
"# def __del__(self): #Overriding\n",
"# return \"Llego el Fin\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"frida = Malinois(\"Frida\")\n",
"print(frida.__dict__)\n",
"\n",
"print(frida.get_section())\n",
"print(frida)\n",
"del(frida)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"## 3.5 Polimorfismo\n",
"Polimorfismo se refiere a la caracteristica de que la misma clase de objeto pueda adquirir varias formas. A diferencia de otros lenguajes como C++ en donde para lograr polimorfismo se requiren de considereciones especiales en la herencia y la sintaxis. En Python el polimorfismo es consecuencia de el tipado dinamico sin tener que tener considerecciones especiales."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.6 Ejercicios\n",
"Como recordarán, el proyecto final consiste en desarrollar un periódico inteligente en el cual, un usuario podrá elegir ciertos temas de interés personal, por ejemplo: ”Política de relaciones exteriores”, ”Francia”, ”Música”, ”Pearl Jam”; y el sistema colectará noticias de diversas fuentes y deberá procesar los documentos para determinar la relevancia de los mismos con respecto a los temas de interés del usuario.\n",
"\n",
"**Instrucciones**: Lea con atención las siguientes especificaciones y diseñe las clases descritas a continuación.\n",
"Diseñe en pyhton las clases siguientes de manera que contengan los atributos y comportamientos necesarios para ser incluidas como parte del proyecto \"periódico inteligente\". No es necesario que implemente los métodos de las clases pero sí es necesario que los declare aunque estén vacios, es decir, el esqueleto de las clases. Considere el uso de los siguientes conceptos:\n",
"\n",
"* constructor\n",
"* variables de instancia\n",
"* variable de clase\n",
"* métodos de instancia\n",
"* métodos de clase\n",
"* herencia\n",
"* polimorfismo\n",
"\n",
"Además de estas clases, puede incluir algunas otras clases que considere necesario incluyendo la justificación. \n",
"\n",
"### 3.6.1 La Clase Nota\n",
"La clase Nota debe abstraer el concepto de una nota periodística; una noticia que aparece en alguna fuente informativa. Algunas características principales de las Notas es que debe pertenecer a alguna categoría como \"deportes\" o \"cultura\", deben tener un título, un autor, una fecha de publicación, entre otros atributos.\n",
"### 3.6.2 La Clase Fuente\n",
"La clase Fuente debe abstraer el concepto de una fuente informativa como por ejemplo \"La Jornada\" o \"noticias MVS\". Una característica principal de las Fuentes es que generan Notas (ver ejercicio 1). \n",
"### 3.6.3 La Clase Editor\n",
"La clase Editor debe abstraer el concepto de una persona (o robot) que se encarga de recopilar las Notas de diversas Fuentes para un determinado tema (sección). Por ejemplo un Editor de la sección \"cultura\" debe ser capaz de identificar las notas que corresponden a este tema. También debe ser capaz de consultar las Fuentes y autores que proporcionan las mejores Notas para la sección que le corresponde, es decir, es experto en uno de los temas. \n",
"### 3.6.4 La Clase Editorial\n",
"La clase Editorial debe abstraer el concepto del consejo editorial de un periódico. Es una clase muy importante para el proyecto ya que la Editorial decide cuáles notas deben aparecer en el día y determina el grado de relevancia de las notas del día para cada sección.Para ello, debe interactuar con los Reporteros para decidir las notas que deben incluirse, considerando los temas de interés y las valoraciones de los Reporteros."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
......
......@@ -12,13 +12,13 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" tricks = [] # Variable de clase\n",
" kind = 'canine' # Variable de clase\n",
" kind = 'Canis Lopus' # Variable de clase\n",
" def __init__(self, name): # Constructor de clase\n",
" self.name = name # Variable de instancia\n",
" def add_trick(self, trick):\n",
......@@ -27,16 +27,16 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 4,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
......@@ -47,7 +47,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 7,
"metadata": {},
"outputs": [
{
......@@ -57,7 +57,7 @@
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-5-629675d46941>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-7-629675d46941>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute 'name'"
]
}
......@@ -68,7 +68,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 8,
"metadata": {},
"outputs": [
{
......@@ -77,7 +77,7 @@
"'Max'"
]
},
"execution_count": 6,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
......@@ -88,7 +88,7 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
......@@ -98,16 +98,16 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 8,
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
......@@ -118,16 +118,16 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 9,
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
......@@ -139,7 +139,7 @@
},
{
"cell_type": "code",
"execution_count": 16,
"execution_count": 12,
"metadata": {},
"outputs": [
{
......@@ -148,7 +148,7 @@
"['roll over', 'play dead']"
]
},
"execution_count": 16,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
......@@ -161,12 +161,12 @@
},
{
"cell_type": "code",
"execution_count": 26,
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" __kind = 'canine' # Variable de clase Privada\n",
" __kind = 'Canis Lopus' # Variable de clase Privada\n",
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" self.tricks = [] # Variable de instancia\n",
......@@ -178,7 +178,7 @@
},
{
"cell_type": "code",
"execution_count": 30,
"execution_count": 14,
"metadata": {},
"outputs": [
{
......@@ -188,7 +188,7 @@
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-30-4cb7b0dc9a4d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__kind\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-14-4cb7b0dc9a4d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__kind\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute '__kind'"
]
}
......@@ -199,23 +199,24 @@
},
{
"cell_type": "code",
"execution_count": 32,
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 32,
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Max = Dog(\"Max\")\n",
"Max.get_kind()\n"
"Max.get_kind()\n",
"Max._Dog__kind"
]
},
{
......@@ -263,11 +264,14 @@
"\n",
"### 3.3.1 Metodos Estaticos\n",
"**@staticmethod**\n",
"Los metodos estatcos no requieren que exista una instancia de la clase y no conocen nada sobre la clase solo sus parametros de entrada.\n",
"Los metodos estaticos no requieren que exista una instancia de la clase y no conocen nada sobre la clase solo sus parametros de entrada.\n",
"\n",
"\n",
"### 3.3.2 Metodos de Clase\n",
"**@classmethod** Los metodos de clase n requiren que exista a una instancia de la clase y tiene acceso a las variables de clase y solo toman como entrada un unico parametro.\n",
"**@classmethod** Los metodos de clase no requiren que exista a una instancia de la clase y tiene acceso a las variables de clase y solo toman como entrada un unico parametro.\n",
"\n",
"### 3.3.3 Set y Get no so Pythonicos\n",
"**@property** y **@*PROPIEDAD*.setter**, permiten acceder y modificar miembros de foma Pythonica.\n",
"\n",
"### 3.3.2 Destructor\n",
"En Python, los destructores no son tan necesarios como en C ++ porque Python tiene un recolector de basura que maneja la administración de la memoria automáticamente.\n",
......@@ -276,22 +280,22 @@
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 59,
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" __kind = 'Canis Lupus' # Variable de clase Privada\n",
" __kind = 'Canis Lopus' # Variable privada de clase, para evitar que se modifique\n",
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" self.tricks = [] # Variable de instancia\n",
" self.tricks = [] # Variable de instancia, para tenenr trucos diferentes por instancia\n",
" self.__age = 0\n",
" @property\n",
" def age(self):\n",
" return self.__age\n",
" @age.setter\n",
" def age(self, age):\n",
" self.__age = age\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" @classmethod\n",
......@@ -308,7 +312,7 @@
},
{
"cell_type": "code",
"execution_count": 60,
"execution_count": 17,
"metadata": {},
"outputs": [
{
......@@ -327,6 +331,7 @@
},
{
"cell_type": "code",
<<<<<<< HEAD
<<<<<<< HEAD
"execution_count": null,
"metadata": {},
......@@ -340,15 +345,18 @@
"## 3.2 Herencia"
=======
"execution_count": 61,
=======
"execution_count": 18,
>>>>>>> 2434cc60fabe38fd65113b4dde7e3818935de3a6
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Canis Lupus'"
"'Canis Lopus'"
]
},
"execution_count": 61,
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
......@@ -358,6 +366,25 @@
>>>>>>> b7f502f0c5394a55521a35097bcdeee698d770be
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"Max = Dog(\"Max\")\n",
"Max.age+=1\n",
"print(Max.age)"
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -467,37 +494,31 @@
},
{
"cell_type": "code",
<<<<<<< HEAD
<<<<<<< HEAD
"execution_count": null,
"metadata": {},
=======
"execution_count": 62,
=======
"execution_count": null,
>>>>>>> 2434cc60fabe38fd65113b4dde7e3818935de3a6
"metadata": {},
"outputs": [],
"source": [
"class Malinois(Dog):\n",
" __age = 0\n",
" origin = \"Bélgica\"\n",
" def fetch(self):\n",
" print(\"fetch\")"
" print(\"Fetch\")"
]
},
{
"cell_type": "code",
"execution_count": 63,
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Canis Lupus\n",
"Max\n",
"[]\n"
]
}
],
"outputs": [],
"source": [
"max = Malinois(\"Max\")\n",
"Max = Malinois(\"Max\")\n",
"print(max.get_kind())\n",
"print(max.name)\n",
"print(max.tricks)"
......@@ -505,14 +526,15 @@
},
{
"cell_type": "code",
"execution_count": 66,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Malinois(Dog):\n",
" __breed = \"Malinois\"\n",
" origin = \"Bélgica\"\n",
" def __init__(self, name):\n",
" Dog.__init__(self, name)\n",
" super().__init__(name) #Dog.__int__(self,name)\n",
" self.tricks = [\"Fetch\"] # Variable de instancia\n",
" def fetch(self):\n",
" print(\"fetch\")\n",
......@@ -523,37 +545,115 @@
},
{
"cell_type": "code",
"execution_count": 67,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"keeper = Malinois(\"Keeper\")\n",
"print(keeper.get_kind())\n",
"print(keeper.name)\n",
"print(keeper.tricks)\n",
"print(keeper)\n",
"del(keeper)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"class Police:\n",
" uniform = \"Azul\"\n",
" def __init__(self, section):\n",
" self.section=section\n",
" def get_section(self):\n",
" return self.section\n",
" def __del__(self): \n",
" print(\"Dia de Jubilacion\") \n",
" \n",
"# Herencia Multiple\n",
"class Malinois(Dog, Police):\n",
" __breed = \"Malinois\"\n",
" origin = \"Bélgica\"\n",
" def __init__(self, name):\n",
" Police.__init__(self,\"K9\")\n",
" #super(__Police__,self).__init__(\"K9\")\n",
" Dog.__init__(self, name) # No usar en herencia multiple\n",
" #super(__Dog__,self).__init__(name)\n",
" self.tricks = [\"fetch\"] # Variable de instancia\n",
" def fetch(self):\n",
" print(\"fetch\")\n",
" def __str__(self): #Overriding\n",
" # Obteniendo variable privada de la clasfridae Padre\n",
" return self.name + \" es un \" + self._Dog__kind + \" Policia de raza \" + self.__breed + \" con uniforme \" + self.uniform\n",
"# def __del__(self): #Overriding\n",
"# return \"Llego el Fin\"\n"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Canis Lupus\n",
"Max\n",
"['Fetch']\n",
"Max es un Canis Lupus de raza Malinois\n",
"Max a muerto\n"
"{'_Dog__age': 0, 'name': 'Frida', 'section': 'K9', 'tricks': ['fetch']}\n",
"K9\n",
"Frida es un Canis Lopus Policia de raza Malinois con uniforme Azul\n",
"Frida a muerto\n"
]
}
],
"source": [
"max = Malinois(\"Max\")\n",
"print(max.get_kind())\n",
"print(max.name)\n",
"print(max.tricks)\n",
"print(max)\n",
"del(max)"
"frida = Malinois(\"Frida\")\n",
"print(frida.__dict__)\n",
"\n",
"print(frida.get_section())\n",
"print(frida)\n",
"del(frida)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.5 Polimorfismo"
"\n",
"\n",
"## 3.5 Polimorfismo\n",
"Polimorfismo se refiere a la caracteristica de que la misma clase de objeto pueda adquirir varias formas. A diferencia de otros lenguajes como C++ en donde para lograr polimorfismo se requiren de considereciones especiales en la herencia y la sintaxis, en Python el polimorfismo es consecuencia de el tipado dinamico sin tener que tener considerecciones especiales."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
......@@ -567,7 +667,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.7 Ejercicios\n",
"## 3.6 Ejercicios\n",
"Como recordarán, el proyecto final consiste en desarrollar un periódico inteligente en el cual, un usuario podrá elegir ciertos temas de interés personal, por ejemplo: ”Política de relaciones exteriores”, ”Francia”, ”Música”, ”Pearl Jam”; y el sistema colectará noticias de diversas fuentes y deberá procesar los documentos para determinar la relevancia de los mismos con respecto a los temas de interés del usuario.\n",
"\n",
"**Instrucciones**: Lea con atención las siguientes especificaciones y diseñe las clases descritas a continuación.\n",
......@@ -583,13 +683,13 @@
"\n",
"Además de estas clases, puede incluir algunas otras clases que considere necesario incluyendo la justificación. \n",
"\n",
"### 3.7.1 La Clase Nota\n",
"### 3.6.1 La Clase Nota\n",
"La clase Nota debe abstraer el concepto de una nota periodística; una noticia que aparece en alguna fuente informativa. Algunas características principales de las Notas es que debe pertenecer a alguna categoría como \"deportes\" o \"cultura\", deben tener un título, un autor, una fecha de publicación, entre otros atributos.\n",
"### 3.7.2 La Clase Fuente\n",
"### 3.6.2 La Clase Fuente\n",
"La clase Fuente debe abstraer el concepto de una fuente informativa como por ejemplo \"La Jornada\" o \"noticias MVS\". Una característica principal de las Fuentes es que generan Notas (ver ejercicio 1). \n",
"### 3.7.3 La Clase Editor\n",
"### 3.6.3 La Clase Editor\n",
"La clase Editor debe abstraer el concepto de una persona (o robot) que se encarga de recopilar las Notas de diversas Fuentes para un determinado tema (sección). Por ejemplo un Editor de la sección \"cultura\" debe ser capaz de identificar las notas que corresponden a este tema. También debe ser capaz de consultar las Fuentes y autores que proporcionan las mejores Notas para la sección que le corresponde, es decir, es experto en uno de los temas. \n",
"### 3.7.4 La Clase Editorial\n",
"### 3.6.4 La Clase Editorial\n",
"La clase Editorial debe abstraer el concepto del consejo editorial de un periódico. Es una clase muy importante para el proyecto ya que la Editorial decide cuáles notas deben aparecer en el día y determina el grado de relevancia de las notas del día para cada sección.Para ello, debe interactuar con los Reporteros para decidir las notas que deben incluirse, considerando los temas de interés y las valoraciones de los Reporteros."
]
},
......@@ -601,6 +701,13 @@
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
......
......@@ -4,7 +4,146 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Examen Unidad 1"
"# 4 Examen Unidad 1\n",
"Escribe una función o classe y su docstring para los siguientes ejercicios. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.1 Obten el promedio de los numeros en una lista."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def ejercicio1(lista):\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.2 Regresa todos los numeros enteros en una lista dividida por un numero."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def ejercicio2(lista, numero):\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.3 Encuentra el factorial de un numero usando recursion.\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"def ejercicio3(numero):\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.4 Encuentra todos los numeros que sean impares y palindromos en un rango dado."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"def ejercicio4(minimo, maximo):\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.5 Escribe una funcion que reciba una plabra y un numero e interactue con el usuario para jugar *ahorcado*, el usuario tiene un numero maximo de intentos para adivinar la palabra:\n",
"[Wikipedia](https://es.wikipedia.org/wiki/Ahorcado_(juego))"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def ejercicio5(palabra, intentos):\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.6 Escribe una funcion que reciva un texto y regrese un diccionario ordenado con el numero de occurencias de cada palabra en el texto."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"def ejercicio6(texto):\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.7 Escribe una clase que convierta un numero entero a numero romano."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"class ejercicio7:\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.8 Escribe una funcion que regrese el cuadrado mágico del tamaño indicado.\n",
"[Wikipedia](https://es.wikipedia.org/wiki/Cuadrado_m%C3%A1gico) Cuadrado Mágico"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"def ejercicio8(n):\n",
" pass"
]
},
{
......@@ -549,7 +688,11 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
<<<<<<< HEAD
"version": "3.7.1"
=======
"version": "3.5.3"
>>>>>>> 2434cc60fabe38fd65113b4dde7e3818935de3a6
}
},
"nbformat": 4,
......
......@@ -4,8 +4,815 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# 2.SciPy\n",
"## 2.1 NumPy"
"![scipy](https://cdn-images-1.medium.com/max/1600/1*Y2v3PrF1rUQRUHwOcXJznA.png)\n",
"\n",
"# 5.SciPy\n",
"SciPy es un ecosistema para computo cientifico en python, esta constriuido sobre los arreglos de NumPy. Scipy incluye herramientas como Matplotlib, pandas , SymPy y scikit-learn. \n",
"\n",
"## 5.1 NumPy\n",
"NumPy es la base para todos los paquetes de computo científico en python, provee soporte para arreglos multidimensionales y matrices, junto con una amplia coleccion de funciones matematicas de alto nivel para operar con estos arreglos.\n",
"\n",
"### 5.1.1 numpy.array \n",
"El tipo de dato mas importante de numpy es **numpy.array** sus atibutos mas importantes son:\n",
"* numpy.array.**ndim**: -numero de dimensiones del arreglo.\n",
"* numpy.array.**shape**: Un tumpla indicando el tamaño del arreglo en cada dimension.\n",
"* numpy.array.**size**: El numero total elementos en el arreglo.\n",
"* numpy.array.**dtype**: El tipo de elemenos en el arreglo e.g. numpy.int32, numpy.int16, and numpy.float64.\n",
"* numpy.array.**itemsize**: el tamaño en bytes de cada elemento del arrglo.\n",
"* numpy.array.**data**: El bloque de memoria que contiene los datos del arreglo.\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0 1 2 3 4]\n",
" [ 5 6 7 8 9]\n",
" [10 11 12 13 14]]\n",
"(3, 5)\n",
"2\n",
"int64\n"
]
}
],
"source": [
"import numpy as np\n",
"a = np.array([[ 0, 1, 2, 3, 4],\n",
" [ 5, 6, 7, 8, 9],\n",
" [10, 11, 12, 13, 14]])\n",
"print(a)\n",
"print(a.shape)\n",
"print(a.ndim)\n",
"print(a.dtype)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[1.+0.j, 2.+0.j],\n",
" [3.+0.j, 4.+0.j]])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c = np.array( [ [1,2], [3,4] ], dtype=complex )\n",
"c"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0., 0., 0., 0.],\n",
" [0., 0., 0., 0.],\n",
" [0., 0., 0., 0.]])"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
" np.zeros( (3,4) )\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[1., 1., 1., 1.],\n",
" [1., 1., 1., 1.],\n",
" [1., 1., 1., 1.]])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.ones( (3,4)) "
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[1., 1., 1., 1.],\n",
" [1., 1., 1., 1.],\n",
" [1., 1., 1., 1.]])"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.empty( (3,4) ) "
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[1., 0., 0., 0., 0.],\n",
" [0., 1., 0., 0., 0.],\n",
" [0., 0., 1., 0., 0.],\n",
" [0., 0., 0., 1., 0.],\n",
" [0., 0., 0., 0., 1.]])"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.eye(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Operaciones Basicas"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"a = np.array([20,30,40,50] )\n",
"b = np.arange( 4 )"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([20, 29, 38, 47])"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Suma\n",
"a-b"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 40, 60, 80, 100])"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiplicacion Por escalar\n",
"a*2"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 4, 9])"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Potencia\n",
"b**2"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ True, True, True, False])"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#Operadores Boleanos\n",
"a<50"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0, 30, 80, 150])"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#Multiplicacion por elemento\n",
"a*b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[**Producto punto**](https://en.wikipedia.org/wiki/Dot_product) y [**Multiplicacion Matricial**](https://en.wikipedia.org/wiki/Matrix_multiplication)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a@b == a.dot(b)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"a = np.array([[1, 0], [0, 1]])\n",
"b = np.array([[4, 1], [2, 2]]) "
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ True, True],\n",
" [ True, True]])"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.matmul(a, b) == a.dot(b)\n"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"66"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c= np.arange(12).reshape(3,4)\n",
"c.sum()"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([12, 15, 18, 21])"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c.sum(axis=0) # Suma por Columna"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 6, 22, 38])"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c.sum(axis=1) #Suma por Fila"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Elementos, filas, columnas y subarreglos."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0, 1, 2, 3],\n",
" [10, 11, 12, 13],\n",
" [20, 21, 22, 23],\n",
" [30, 31, 32, 33],\n",
" [40, 41, 42, 43]])"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def f(x,y):\n",
" return 10*x+y\n",
"b = np.fromfunction(f,(5,4),dtype=int)\n",
"b"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b[0,3]"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([10, 11, 12, 13])"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b[1,:]"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 1, 11, 21, 31, 41])"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b[:,1]"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 1, 2],\n",
" [11, 12]])"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b[:2,1:3]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Iterando elementos"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0 1 2 3]\n",
"[10 11 12 13]\n",
"[20 21 22 23]\n",
"[30 31 32 33]\n",
"[40 41 42 43]\n"
]
}
],
"source": [
"for row in b:\n",
" print(row)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"10\n",
"11\n",
"12\n",
"13\n",
"20\n",
"21\n",
"22\n",
"23\n",
"30\n",
"31\n",
"32\n",
"33\n",
"40\n",
"41\n",
"42\n",
"43\n"
]
}
],
"source": [
"for element in b.flat:\n",
" print(element)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Cambio de forma"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[8., 0., 8., 9.],\n",
" [6., 1., 5., 9.],\n",
" [9., 3., 3., 2.]])"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = np.floor(10*np.random.random((3,4)))\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(3, 4)"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a.shape"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[8., 0.],\n",
" [8., 9.],\n",
" [6., 1.],\n",
" [5., 9.],\n",
" [9., 3.],\n",
" [3., 2.]])"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a.reshape(6,2)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[8., 6., 9.],\n",
" [0., 1., 3.],\n",
" [8., 5., 3.],\n",
" [9., 9., 2.]])"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a.T"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ True, True, True],\n",
" [ True, True, True],\n",
" [ True, True, True],\n",
" [ True, True, True]])"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a.transpose()==a.T"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(4, 3)"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a.T.shape"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[8., 0., 8., 9.],\n",
" [6., 1., 5., 9.],\n",
" [9., 3., 3., 2.]])"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# La dimencion con -1 se calcula automaticamente\n",
"a.reshape(3,-1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5.2 Ejercicos\n",
"\n",
"### 5.2.1 Sin utilizar numpy escribe una funcion para obten el producto punto de dos vectores."
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [],
"source": [
"a = [2, 5.6, 9, 8, 10]\n",
"b = [1, 3, 2.4, 2, 11]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 5.2.2 Sin utilizar numpy escribe una funcion que obtenga la multiplicacion de dos matrices.\n"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"A = [[1,2,3],[4,5,6]]\n",
"B = [[7,8],[9,10],[11,12]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 5.2.3 Utiliza numpy para probar que las dos funciones anteriores dan el resultado correcto."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 5.2.4 Utilizando solo lo visto hasta el momento de numpy escribe una funcion que encuentre la inversa de una matriz por el metodo de Gauss-Jordan.\n",
"[Wikipedia](https://en.wikipedia.org/wiki/Gaussian_elimination): En matemáticas, la eliminación de Gauss Jordan, llamada así en honor de Carl Friedrich Gauss y Wilhelm Jordan es un algoritmo del álgebra lineal que se usa para determinar las soluciones de un sistema de ecuaciones lineales, para encontrar matrices e inversas. Un sistema de ecuaciones se resuelve por el método de Gauss cuando se obtienen sus soluciones mediante la reducción del sistema dado a otro equivalente en el que cada ecuación tiene una incógnita menos que la anterior. El método de Gauss transforma la matriz de coeficientes en una matriz triangular superior. El método de Gauss-Jordan continúa el proceso de transformación hasta obtener una matriz diagonal"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 5.2.5 Utilizando la funcion anterior escribe otra que obtenga la pseduo-inversa de una matriz."
]
},
{
......@@ -19,7 +826,386 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2.2 Pandas"
"## 5.3 Pandas\n",
"En python, pandas es una biblioteca de software escrita como extensión de NumPy para manipulación y análisis de datos. En particular, ofrece estructuras de datos y operaciones para manipular tablas numéricas y series temporales.\n",
"and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. Su objetivo es ser un bloque de construccion fundamental para realizar analisis de datos en el mundo real.\n",
"El nombre de la biblioteca deriva del término \"datos de panel\" (PANel DAta), término de econometría que designa datos que combinan una dimensión temporal con otra dimensión transversal.\n",
"\n",
"Pandas tiene dos typos de datos principales, **Series** (1D) y **DataFrame** (2D), *Dataframe* es un contenedr para *Series* y *Series* es un contenedor de escalares. \n",
"\n",
"### 5.3.1 Series\n",
"Series es un arreglo unidimensional etiquetado capaz de contener cualquier tipo de dato (Enteros, cadenas, punto flotante, objetos, etc), El eje de etiquetas es llamado indice (**index**).\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"a 0.994272\n",
"b 0.530519\n",
"c 1.162452\n",
"d -0.981436\n",
"e -1.283798\n",
"dtype: float64"
]
},
"execution_count": 51,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])\n",
"s"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0 2.042498\n",
"1 -0.964070\n",
"2 -0.687132\n",
"3 0.623300\n",
"4 1.366322\n",
"dtype: float64"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.Series(np.random.randn(5))"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"a 0\n",
"b 1\n",
"c 2\n",
"dtype: int64"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"d = {'b': 1, 'a': 0, 'c': 2}\n",
"pd.Series(d)"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"b 1.0\n",
"c 2.0\n",
"d NaN\n",
"a 0.0\n",
"dtype: float64"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"d = {'a': 0., 'b': 1., 'c': 2.}\n",
"pd.Series(d, index=['b', 'c', 'd', 'a'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Las Series son compatibles con *numpy.array* y *dict*"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.9942721192063438"
]
},
"execution_count": 53,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s[0]"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"a 0.994272\n",
"b 0.530519\n",
"c 1.162452\n",
"dtype: float64"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s[:3]"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"a 0.994272\n",
"b 0.530519\n",
"c 1.162452\n",
"dtype: float64"
]
},
"execution_count": 55,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s[s>s.mean()]"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"a 1.988544\n",
"b 1.061037\n",
"c 2.324904\n",
"d -1.962872\n",
"e -2.567597\n",
"dtype: float64"
]
},
"execution_count": 56,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s*2"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"a True\n",
"b False\n",
"c True\n",
"d False\n",
"e False\n",
"dtype: bool"
]
},
"execution_count": 57,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s>s.median()"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.9942721192063438"
]
},
"execution_count": 58,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s[\"a\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Alieneacion Automatica"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [],
"source": [
"a = np.array(range(10))\n",
"s = pd.Series(a)"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])"
]
},
"execution_count": 60,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0 0\n",
"1 1\n",
"2 2\n",
"3 3\n",
"4 4\n",
"5 5\n",
"6 6\n",
"7 7\n",
"8 8\n",
"9 9\n",
"dtype: int64"
]
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 4, 6, 8, 10, 12, 14])"
]
},
"execution_count": 75,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(a[:6]+a[4:])"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0 NaN\n",
"1 NaN\n",
"2 NaN\n",
"3 NaN\n",
"4 8.0\n",
"5 10.0\n",
"6 NaN\n",
"7 NaN\n",
"8 NaN\n",
"9 NaN\n",
"dtype: float64"
]
},
"execution_count": 76,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(s[:6]+s[4:])"
]
},
{
......@@ -46,7 +1232,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8rc1"
"version": "3.7.1"
}
},
"nbformat": 4,
......
# Tópicos Avanzados de Programación
## Instalación de Herramientas
```bash
sudo apt-get install python3 pip3
python3 -m pip install --upgrade pip
pip3 install jupyter
```
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 3. Programacion Orientada a Objetos\n",
"## 3.1 Clases \n",
"\n",
"Las clases proporcionan un medio de agrupar datos y funcionalidad. La creación de una nueva clase crea un nuevo tipo de objeto, lo que permite crear nuevas instancias de ese objeto. Cada instancia de la clase puede tener atributos adjuntos para mantener su estado. Las instancias de clase también pueden tener métodos (definidos por su clase) para modificar su estado."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" tricks = [] # Variable de clase\n",
" kind = 'canine' # Variable de clase\n",
" def __init__(self, name): # Constructor de clase\n",
" self.name = name # Variable de instancia\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" def f(self):\n",
" var=1 # variable local al método\n",
" return var"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"pastis\n"
]
}
],
"source": [
"pastis=Dog(\"pastis\")\n",
"print(pastis.name)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Dog.kind\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "type object 'Dog' has no attribute 'name'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-5-629675d46941>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute 'name'"
]
}
],
"source": [
"Dog.name"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Max'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Dog(\"Max\").name"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"Max = Dog(\"Max\")\n",
"Keeper = Dog(\"Keeper\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Max.kind"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Max.kind=\"felis\"\n",
"Keeper.kind"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['roll over', 'play dead']"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Max.add_trick('roll over')\n",
"Max.add_trick('play dead')\n",
"Keeper.tricks\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" __kind = 'canine' # Variable de clase Privada\n",
" name = \"\"\n",
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" self.tricks = [] # Variable de instancia\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" def get_kind(self):\n",
" return self.__kind"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "type object 'Dog' has no attribute '__kind'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-9-4cb7b0dc9a4d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__kind\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute '__kind'"
]
}
],
"source": [
"Dog.__kind"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Max = Dog(\"Max\")\n",
"Max.get_kind()\n",
"Max._Dog__kind\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notas:\n",
"* **Self** no es una palabra reservada en Python solo una convencion.\n",
"* [\"why explicit self has to stay\", por Guido van Rossum](http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html)\n",
"* [We are all consenting adults](https://python-guide-chinese.readthedocs.io/zh_CN/latest/writing/style.html#we-are-all-consenting-adults) Python permite muchos trucos, y algunos de ellos son potencialmente peligrosos. Un buen ejemplo es que cualquier código de cliente puede anular las propiedades y los métodos de un objeto: no hay una palabra clave \"privada\" en Python. Esta filosofía, muy diferente de los lenguajes altamente defensivos como Java, que ofrecen muchos mecanismos para evitar cualquier uso indebido, se expresa con el dicho: \"Todos somos adultos\".\n",
"\n",
"## 3.3 Decoradores \n",
"Los decoradores son una conveniencia sintáctica, que permite que un archivo fuente de Python diga qué va a hacer con el resultado de una función o una declaración de clase antes de la declaración.\n",
"\n",
"### 3.3.1 Metodos Estaticos\n",
"**@staticmethod**\n",
"Los metodos estatcos no requieren que exista una instancia de la clase y no conocen nada sobre la clase solo sus parametros de entrada.\n",
"\n",
"\n",
"### 3.3.2 Metodos de Clase\n",
"**@classmethod** Los metodos de clase n requiren que exista a una instancia de la clase y tiene acceso a las variables de clase y solo toman como entrada un unico parametro.\n",
"\n",
"### 3.3.2 Destructor\n",
"En Python, los destructores no son tan necesarios como en C ++ porque Python tiene un recolector de basura que maneja la administración de la memoria automáticamente.\n",
"El método **__del __ ()** es el método conocido como destructor en Python. Se llama cuando todas las referencias al objeto se han eliminado, es decir, cuando un objeto se recolecta como basura."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" __kind = 'Canis Lupus' # Variable de clase Privada\n",
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" self.tricks = [] # Variable de instancia\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" @classmethod\n",
" def get_kind(cls):\n",
" return cls.__kind\n",
" @staticmethod\n",
" def bark(times):\n",
" print(\"Guau \"*times)\n",
" def __str__(self):\n",
" return self.name + \" es un \" + self.__kind\n",
" def __del__(self): \n",
" print(self.name + \" a muerto\") "
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau \n"
]
}
],
"source": [
"Dog.bark(30)\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Canis Lupus'"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Dog.get_kind()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.4 Herencia"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"class Pet():\n",
" def __init__(self, owner_name):\n",
" self.owner=owner_name"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"class Malinois(Dog, Pet):\n",
" __breed = \"Malinois\"\n",
" def __init__(self, name, ownername):\n",
" Dog.__init__(self, name)\n",
" Pet.__init__(self, ownername)\n",
" self.tricks = [\"Fetch\"] # Variable de instancia\n",
" def fetch(self):\n",
" print(\"fetch\")\n",
" def __str__(self): #Overriding\n",
" # Obteniendo variable privada de la clase Padre\n",
" return self.name + \" es un \" + self._Dog__kind + \" de raza \" + self.__breed"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Canis Lupus\n",
"Max\n",
"['Fetch']\n",
"Alex\n",
"Max a muerto\n"
]
}
],
"source": [
"max = Malinois(\"Max\", \"Alex\")\n",
"print(max.get_kind())\n",
"print(max.name)\n",
"print(max.tricks)\n",
"print(max.owner)\n",
"del(max)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.5 Polimorfismo"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.7 Ejercicios\n",
"Como recordarán, el proyecto final consiste en desarrollar un periódico inteligente en el cual, un usuario podrá elegir ciertos temas de interés personal, por ejemplo: ”Política de relaciones exteriores”, ”Francia”, ”Música”, ”Pearl Jam”; y el sistema colectará noticias de diversas fuentes y deberá procesar los documentos para determinar la relevancia de los mismos con respecto a los temas de interés del usuario.\n",
"\n",
"**Instrucciones**: Lea con atención las siguientes especificaciones y diseñe las clases descritas a continuación.\n",
"Diseñe en pyhton las clases siguientes de manera que contengan los atributos y comportamientos necesarios para ser incluidas como parte del proyecto \"periódico inteligente\". No es necesario que implemente los métodos de las clases pero sí es necesario que los declare aunque estén vacios, es decir, el esqueleto de las clases. Considere el uso de los siguientes conceptos:\n",
"\n",
"* constructor\n",
"* variables de instancia\n",
"* variable de clase\n",
"* métodos de instancia\n",
"* métodos de clase\n",
"* herencia\n",
"* polimorfismo\n",
"\n",
"Además de estas clases, puede incluir algunas otras clases que considere necesario incluyendo la justificación. \n",
"\n",
"### 3.7.1 La Clase Nota\n",
"La clase Nota debe abstraer el concepto de una nota periodística; una noticia que aparece en alguna fuente informativa. Algunas características principales de las Notas es que debe pertenecer a alguna categoría como \"deportes\" o \"cultura\", deben tener un título, un autor, una fecha de publicación, entre otros atributos.\n",
"### 3.7.2 La Clase Fuente\n",
"La clase Fuente debe abstraer el concepto de una fuente informativa como por ejemplo \"La Jornada\" o \"noticias MVS\". Una característica principal de las Fuentes es que generan Notas (ver ejercicio 1). \n",
"### 3.7.3 La Clase Editor\n",
"La clase Editor debe abstraer el concepto de una persona (o robot) que se encarga de recopilar las Notas de diversas Fuentes para un determinado tema (sección). Por ejemplo un Editor de la sección \"cultura\" debe ser capaz de identificar las notas que corresponden a este tema. También debe ser capaz de consultar las Fuentes y autores que proporcionan las mejores Notas para la sección que le corresponde, es decir, es experto en uno de los temas. \n",
"### 3.7.4 La Clase Editorial\n",
"La clase Editorial debe abstraer el concepto del consejo editorial de un periódico. Es una clase muy importante para el proyecto ya que la Editorial decide cuáles notas deben aparecer en el día y determina el grado de relevancia de las notas del día para cada sección.Para ello, debe interactuar con los Reporteros para decidir las notas que deben incluirse, considerando los temas de interés y las valoraciones de los Reporteros."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
No preview for this file type
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment