Commit 3b5c1109 authored by Carlos David García Hernández's avatar Carlos David García Hernández

examen 1

parents ee35fc97 2b2c0d29
install.packages("car")
library(car)
install.packages("rgl")
q()
......@@ -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"
]
},
{
......
......@@ -251,7 +251,7 @@
},
{
"cell_type": "code",
"execution_count": 55,
"execution_count": 2,
"metadata": {},
"outputs": [
{
......@@ -307,6 +307,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": 39,
"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,370 @@
},
{
"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": 40,
"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": "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": [
"Max = Dog(\"Max\")\n",
"Max.get_kind()\n",
"Max._Dog__kind"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.2 Herencia"
"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": 41,
"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 #Get\n",
" def age(self):\n",
" return self.__age\n",
" @age.setter #Set\n",
" def age(self, value):\n",
" self.__age = value\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" @classmethod\n",
" def get_kind(cls):\n",
" return cls.__kind\n",
" @staticmethod #Solo bark es 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": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau \n"
]
}
],
"source": [
"Dog.bark(10)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Canis Lopus'"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Dog.get_kind()"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Max a muerto\n",
"1\n"
]
}
],
"source": [
"Max = Dog(\"Max\")\n",
"Max.age+=1\n",
"print(Max.age)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.3 Polimorfismo"
"## 3.4 Herencia"
]
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"class Malinois(Dog):\n",
" origin = \"Bélgica\"\n",
" def fetch(self):\n",
" print(\"Fetch\")"
]
},
{
"cell_type": "code",
"execution_count": 46,
"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": [
"Canis Lopus\n",
"Maximus\n",
"[]\n"
]
}
],
"source": [
"Maximus = Malinois(\"Maximus\")\n",
"print(Max.get_kind())\n",
"print(Max.name)\n",
"print(Max.tricks)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"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": 48,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Canis Lopus\n",
"Keeper\n",
"['Fetch']\n",
"Keeper es un Canis Lopus de raza Malinois\n",
"Keeper a muerto\n"
]
}
],
"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": 50,
"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": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'name': 'Frida', 'tricks': ['fetch'], 'section': 'K9', '_Dog__age': 0}\n",
"K9\n",
"Frida es un Canis Lopus Policia de raza Malinois con uniforme Azul\n"
]
}
],
"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": []
},
{
......@@ -186,6 +511,158 @@
"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": 117,
"metadata": {},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"class Nota:\n",
" def __init__(self,text,section,author,title,date=datetime.today(),source=None):\n",
" self.text=text\n",
" self.section=section\n",
" self.author=author\n",
" self.date=date\n",
" self.title=title\n",
" self.source=source\n",
" \n",
" def __str__(self):\n",
" out=\"\"\n",
" out+=self.title+\"\\t\"+self.date.strftime(\"%m-%d-%y\")+\"\\n\"\n",
" out+=self.author+\"\\n\"\n",
" out+=\"Sección: \"+self.section+\"\\n\"\n",
" if self.source.nombre is not None:\n",
" out+=self.source.nombre+\"\\n\"\n",
" out+=\"\\n\"+self.text\n",
" return out\n",
" \n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": 118,
"metadata": {},
"outputs": [],
"source": [
"miNota=Nota(\"Este es el contenido de la nota\",\"Investigacion\",\"CGarcia\",\"Titulo de la nota\")\n",
"Editorial=Fuente(\"La Jornada\", \"http://jornada.unam.mx\")\n",
"miNota.source=Editorial"
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Titulo de la nota\t02-05-19\n",
"CGarcia\n",
"Sección: Investigacion\n",
"La Jornada\n",
"\n",
"Este es el contenido de la nota\n"
]
}
],
"source": [
"print(miNota)"
]
},
{
"cell_type": "code",
"execution_count": 116,
"metadata": {},
"outputs": [],
"source": [
"class Fuente:\n",
" def __init__(self,nombre,url):\n",
" self.nombre=nombre\n",
" self.url=url\n",
" \n",
" def __str__(self):\n",
" return str(self.nombre)\n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": 120,
"metadata": {},
"outputs": [],
"source": [
"class Editor:\n",
" def __init__(self, topic):\n",
" self.topic=topic\n",
" \n",
" \n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": 122,
"metadata": {},
"outputs": [],
"source": [
"class Editorial:\n",
" pass"
]
}
],
"metadata": {
......@@ -204,7 +681,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.3"
"version": "3.5.2"
}
},
"nbformat": 4,
......
......@@ -4,15 +4,670 @@
"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": "code",
"execution_count": null,
"execution_count": 208,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n"
]
}
],
"source": [
"#lista para los ejercicios\n",
"lista=[]\n",
"for i in range(11):\n",
" lista.append(i)\n",
" \n",
"print(lista)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.1 Obten el promedio de los numeros en una lista."
]
},
{
"cell_type": "code",
"execution_count": 210,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"12.5\n",
"5.0\n"
]
}
],
"source": [
"def ejercicio1(lista):\n",
" suma=0\n",
" div=None\n",
" for num in lista:\n",
" suma+=num\n",
" div=(suma/len(lista))\n",
" print(div)\n",
"\n",
"ejercicio1([5,10,15,20])\n",
"ejercicio1(lista)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.2 Regresa todos los numeros enteros en una lista dividida por un numero."
]
},
{
"cell_type": "code",
"execution_count": 211,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{0, 1, 2, 3}\n"
]
}
],
"source": [
"def ejercicio2(lista, numero):\n",
" listaEnt=[x//numero for x in lista]\n",
" setEnt=set(listaEnt)\n",
" print(setEnt)\n",
" \n",
"ejercicio2(lista,3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.3 Encuentra el factorial de un numero usando recursion.\n"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"120"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def ejercicio3(numero):\n",
" if numero == 1:\n",
" return numero\n",
" else:\n",
" return numero*ejercicio3(numero-1)\n",
"\n",
"ejercicio3(5)"
]
},
{
"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": 206,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"Es palindromo\n",
"2\n",
"Es palindromo\n",
"3\n",
"Es palindromo\n",
"4\n",
"Es palindromo\n",
"5\n",
"Es palindromo\n",
"6\n",
"Es palindromo\n",
"7\n",
"Es palindromo\n",
"8\n",
"Es palindromo\n",
"9\n",
"Es palindromo\n",
"10\n",
"No es palindromo\n",
"11\n",
"Es palindromo\n",
"12\n",
"No es palindromo\n",
"13\n",
"No es palindromo\n",
"14\n",
"No es palindromo\n",
"15\n",
"No es palindromo\n",
"16\n",
"No es palindromo\n",
"17\n",
"No es palindromo\n",
"18\n",
"No es palindromo\n",
"19\n",
"No es palindromo\n",
"20\n",
"No es palindromo\n",
"21\n",
"No es palindromo\n",
"22\n",
"Es palindromo\n",
"23\n",
"No es palindromo\n",
"24\n",
"No es palindromo\n",
"25\n",
"No es palindromo\n",
"26\n",
"No es palindromo\n",
"27\n",
"No es palindromo\n",
"28\n",
"No es palindromo\n",
"29\n",
"No es palindromo\n",
"30\n",
"No es palindromo\n",
"31\n",
"No es palindromo\n",
"32\n",
"No es palindromo\n",
"33\n",
"Es palindromo\n",
"34\n",
"No es palindromo\n",
"35\n",
"No es palindromo\n",
"36\n",
"No es palindromo\n",
"37\n",
"No es palindromo\n",
"38\n",
"No es palindromo\n",
"39\n",
"No es palindromo\n",
"40\n",
"No es palindromo\n",
"41\n",
"No es palindromo\n",
"42\n",
"No es palindromo\n",
"43\n",
"No es palindromo\n",
"44\n",
"Es palindromo\n",
"45\n",
"No es palindromo\n",
"46\n",
"No es palindromo\n",
"47\n",
"No es palindromo\n",
"48\n",
"No es palindromo\n",
"49\n",
"No es palindromo\n",
"50\n",
"No es palindromo\n",
"51\n",
"No es palindromo\n",
"52\n",
"No es palindromo\n",
"53\n",
"No es palindromo\n",
"54\n",
"No es palindromo\n",
"55\n",
"Es palindromo\n",
"56\n",
"No es palindromo\n",
"57\n",
"No es palindromo\n",
"58\n",
"No es palindromo\n",
"59\n",
"No es palindromo\n",
"60\n",
"No es palindromo\n",
"61\n",
"No es palindromo\n",
"62\n",
"No es palindromo\n",
"63\n",
"No es palindromo\n",
"64\n",
"No es palindromo\n",
"65\n",
"No es palindromo\n",
"66\n",
"Es palindromo\n",
"67\n",
"No es palindromo\n",
"68\n",
"No es palindromo\n",
"69\n",
"No es palindromo\n",
"70\n",
"No es palindromo\n",
"71\n",
"No es palindromo\n",
"72\n",
"No es palindromo\n",
"73\n",
"No es palindromo\n",
"74\n",
"No es palindromo\n",
"75\n",
"No es palindromo\n",
"76\n",
"No es palindromo\n",
"77\n",
"Es palindromo\n",
"78\n",
"No es palindromo\n",
"79\n",
"No es palindromo\n",
"80\n",
"No es palindromo\n",
"81\n",
"No es palindromo\n",
"82\n",
"No es palindromo\n",
"83\n",
"No es palindromo\n",
"84\n",
"No es palindromo\n",
"85\n",
"No es palindromo\n",
"86\n",
"No es palindromo\n",
"87\n",
"No es palindromo\n",
"88\n",
"Es palindromo\n",
"89\n",
"No es palindromo\n",
"90\n",
"No es palindromo\n",
"91\n",
"No es palindromo\n",
"92\n",
"No es palindromo\n",
"93\n",
"No es palindromo\n",
"94\n",
"No es palindromo\n",
"95\n",
"No es palindromo\n",
"96\n",
"No es palindromo\n",
"97\n",
"No es palindromo\n",
"98\n",
"No es palindromo\n",
"99\n",
"Es palindromo\n",
"100\n",
"No es palindromo\n",
"101\n",
"Es palindromo\n",
"Lista de palindromos: \n",
"\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101]\n",
"Lista de palindromos e impares: \n",
"\n",
"[1, 3, 5, 7, 9, 11, 33, 55, 77, 99, 101]\n"
]
}
],
"source": [
"listaejem=[]\n",
"\n",
"def ejercicio4(minimo, maximo):\n",
" for i in range(minimo,maximo):\n",
" print(i)\n",
" aux=i\n",
" rev=0\n",
" while(i>0):\n",
" digito=i%10\n",
" rev=rev*10+digito\n",
" i=i//10\n",
" if(aux==rev):\n",
" listaejem.append(aux)\n",
" print(\"Es palindromo\")\n",
" else:\n",
" print(\"No es palindromo\")\n",
" \n",
" print(\"Lista de palindromos: \\n\")\n",
" print(listaejem)\n",
" \n",
" imparlista=[impar for impar in listaejem if impar%2==1]\n",
" print(\"Lista de palindromos e impares: \\n\")\n",
" print(imparlista)\n",
"\n",
"ejercicio4(1,102)"
]
},
{
"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": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dime una palabra: hola\n",
"['_', '_', '_', '_']\n",
"Dame una letra: q\n",
"\n",
"te quedan 1 intentos!\n",
"\n",
"['_', '_', '_', '_']\n",
"Dame una letra: q\n",
"\n",
"te quedan 0 intentos!\n",
"\n",
"Ya perdiste! -_-\n",
" la palabra era: \n",
"['h', 'o', 'l', 'a']\n"
]
}
],
"source": [
"def ejercicio5(intentos=2):\n",
" palabra = ''\n",
" listaPalabra = []\n",
" listaPalabraEspacio = []\n",
" letra = ''\n",
" detente= 1\n",
" \n",
" palabra= str(input('Dime una palabra: '))\n",
" palabra=palabra.lower()\n",
" listaPalabra=list(palabra)\n",
" for palabr in listaPalabra:\n",
" listaPalabraEspacio.append('_')\n",
" \n",
" while detente==1:\n",
" print(listaPalabraEspacio)\n",
" letra = input('Dame una letra: ')\n",
" fallo = False\n",
" if letra not in listaPalabra:\n",
" fallo = True\n",
" intentos=intentos-1\n",
" print(\"\\nte quedan \"+ str(intentos)+\" intentos!\\n\")\n",
" \n",
" else: \n",
" for key, value in enumerate(listaPalabra):\n",
" if value == letra:\n",
" listaPalabraEspacio[key] = value\n",
" \n",
" if intentos <= 0:\n",
" detente= 0\n",
" print(\"Ya perdiste! -_-\\n la palabra era: \\n\"+ str(listaPalabra))\n",
" elif listaPalabra == listaPalabraEspacio:\n",
" detente= 0 \n",
" print(\"Ya ganaste! ͡° ͜ʖ ͡° \\n la palabra era \\n\"+str(listaPalabra))\n",
" \n",
"ejercicio5()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.6 Escribe una funcion que reciba un texto y regrese un diccionario ordenado con el numero de ocurrencias de cada palabra en el texto."
]
},
{
"cell_type": "code",
"execution_count": 201,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Escriba su texto: \n",
"hola mundo infeliz hola\n",
"['hola', 'mundo', 'infeliz', 'hola']\n",
"{'hola': 2, 'mundo': 1, 'infeliz': 1}\n"
]
}
],
"source": [
"dicti={}\n",
"\n",
"def ejercicio6():\n",
" texto=str(input(\"Escriba su texto: \\n\"))\n",
" texto=texto.split()\n",
" print(texto)\n",
" for palabra in texto:\n",
" dicti.update({palabra:texto.count(palabra)})\n",
" print(dicti)\n",
" \n",
"ejercicio6()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.7 Escribe una clase que convierta un numero entero a numero romano."
]
},
{
"cell_type": "code",
"execution_count": 319,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ingresar número (Cero para terminar el programa):10\n",
"10:\n",
"X\n",
"Ingresar número (Cero para terminar el programa):24\n",
"24:\n",
"XXIV\n",
"Ingresar número (Cero para terminar el programa):0\n"
]
}
],
"source": [
"enteros= [1000, 900, 500, 400,100, 90, 50, 40,10, 9, 5, 4,1] \n",
"Letras = [\"M\", \"CM\", \"D\", \"CD\",\"C\", \"XC\", \"L\", \"XL\",\"X\", \"IX\", \"V\", \"IV\",\"I\"]\n",
"romano=\"\"\n",
"while True:\n",
" x=int(input(\"Ingresar número (Cero para terminar el programa):\"))\n",
" if(x==0):\n",
" break\n",
" print(str(x)+\":\")\n",
" i=0\n",
" \n",
" while (x>0):\n",
" if(x>=enteros[i]):\n",
" x=x-enteros[i]\n",
" romano+=Letras[i]\n",
" else:\n",
" i=i+1\n",
" print(romano)\n",
" romano=\"\""
]
},
{
"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": 278,
"metadata": {},
"outputs": [],
"source": []
"source": [
"import numpy as np\n",
"import random as rnd"
]
},
{
"cell_type": "code",
"execution_count": 318,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ingresa el tamaño del cuadrado: \n",
"3\n",
"[[0. 0. 0.]\n",
" [0. 0. 0.]\n",
" [0. 0. 0.]]\n",
"-----\n",
"soy j:1\n",
"[[0. 1. 0.]\n",
" [0. 0. 0.]\n",
" [0. 0. 0.]]\n",
"-----\n",
"soy j:2\n",
"[[0. 1. 0.]\n",
" [0. 0. 0.]\n",
" [0. 0. 2.]]\n",
"-----\n",
"soy j:0\n",
"1.0\n",
"La celda esta ocupada, regresa e inserta abajo\n",
"[[0. 1. 0.]\n",
" [3. 0. 0.]\n",
" [0. 0. 2.]]\n",
"-----\n",
"soy j:0\n",
"[[0. 1. 0.]\n",
" [3. 0. 0.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:1\n",
"[[0. 1. 0.]\n",
" [3. 5. 0.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:2\n",
"4.0\n",
"La celda esta ocupada, regresa e inserta abajo\n",
"[[0. 1. 6.]\n",
" [3. 5. 0.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:2\n",
"[[0. 1. 6.]\n",
" [3. 5. 7.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:0\n",
"[[8. 1. 6.]\n",
" [3. 5. 7.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:1\n",
"7.0\n",
"La celda esta ocupada, regresa e inserta abajo\n",
"[[8. 1. 6.]\n",
" [3. 5. 7.]\n",
" [4. 9. 2.]]\n",
"-----\n",
"[[8. 1. 6.]\n",
" [3. 5. 7.]\n",
" [4. 9. 2.]]\n"
]
}
],
"source": [
"def ejercicio8():\n",
" tam=input(\"Ingresa el tamaño del cuadrado: \\n\")\n",
" tam=int(tam)\n",
" magico=np.zeros((tam,tam))\n",
" print(magico)\n",
" print(\"-----\")\n",
" if tam==2:\n",
" print(\"no hay solucion :v\")\n",
" \n",
" if tam%2==1:\n",
" #inicializacion\n",
" n = 1\n",
" i, j = 0, tam//2\n",
" \n",
" #numero de elementos\n",
" while n <= tam**2:\n",
" print(\"soy j:\"+str(j))\n",
" magico[i, j] = n\n",
" \n",
" #Siguiente movimiento\n",
" n += 1\n",
" movi, movj = (i-1) % tam, (j+1)% tam\n",
" \n",
" if magico[movi, movj]:\n",
" print(magico[movi,movj])\n",
" print(\"La celda esta ocupada, regresa e inserta abajo\")\n",
" i += 1\n",
" else:\n",
" i, j = movi, movj\n",
" \n",
" print(magico)\n",
" print(\"-----\")\n",
" \n",
" #pares mayores de dos \n",
" elif ((tam!=2) and (tam%2==0)):\n",
" print(\"no se hacerlo\")\n",
" \n",
" print(magico)\n",
"ejercicio8()"
]
}
],
"metadata": {
......@@ -31,7 +686,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8rc1"
"version": "3.5.2"
}
},
"nbformat": 4,
......
......@@ -894,7 +894,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 10,
"metadata": {},
"outputs": [
{
......@@ -1360,6 +1360,74 @@
" \n",
"piramide()"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"wrote tarea2_ejercicios1.html\n"
]
}
],
"source": [
"%%bash\n",
"cd miModulo\n",
"pydoc -w tarea2_ejercicios1"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n",
"<html><head><title>Python: module tarea2_ejercicios1</title>\n",
"<meta charset=\"utf-8\">\n",
"</head><body bgcolor=\"#f0f0f8\">\n",
"\n",
"<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"heading\">\n",
"<tr bgcolor=\"#7799ee\">\n",
"<td valign=bottom>&nbsp;<br>\n",
"<font color=\"#ffffff\" face=\"helvetica, arial\">&nbsp;<br><big><big><strong>tarea2_ejercicios1</strong></big></big></font></td\n",
"><td align=right valign=bottom\n",
"><font color=\"#ffffff\" face=\"helvetica, arial\"><a href=\".\">index</a><br><a href=\"file:/home/carlosgarcia8/repos/tap1012/miModulo/tarea2_ejercicios1.py\">/home/carlosgarcia8/repos/tap1012/miModulo/tarea2_ejercicios1.py</a></font></td></tr></table>\n",
" <p><tt>Documentación&nbsp;para&nbsp;la&nbsp;segunda&nbsp;tarea&nbsp;(ejercicios&nbsp;1)&nbsp;de&nbsp;la&nbsp;materia&nbsp;de&nbsp;Tópicos&nbsp;Avanzados&nbsp;de&nbsp;Programación.<br>\n",
"Maestría&nbsp;GeoInteligencia&nbsp;Computacional&nbsp;a&nbsp;27&nbsp;de&nbsp;Enero&nbsp;del&nbsp;2019.</tt></p>\n",
"<p>\n",
"<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"section\">\n",
"<tr bgcolor=\"#eeaa77\">\n",
"<td colspan=3 valign=bottom>&nbsp;<br>\n",
"<font color=\"#ffffff\" face=\"helvetica, arial\"><big><strong>Functions</strong></big></font></td></tr>\n",
" \n",
"<tr><td bgcolor=\"#eeaa77\"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>\n",
"<td width=\"100%\"><dl><dt><a name=\"-coincide\"><strong>coincide</strong></a>(l1, l2)</dt><dd><tt>Función&nbsp;que&nbsp;devuelve&nbsp;todos&nbsp;los&nbsp;elementos&nbsp;coincidentes&nbsp;de&nbsp;un&nbsp;par&nbsp;de&nbsp;listas&nbsp;que&nbsp;el&nbsp;usuario&nbsp;pase&nbsp;como&nbsp;argumento</tt></dd></dl>\n",
" <dl><dt><a name=\"-numerMay\"><strong>numerMay</strong></a>(l1)</dt><dd><tt>Función&nbsp;que&nbsp;devuelve&nbsp;los&nbsp;números&nbsp;estrictamente&nbsp;mayores&nbsp;a&nbsp;10&nbsp;de&nbsp;una&nbsp;lista&nbsp;que&nbsp;el&nbsp;usuario&nbsp;pase&nbsp;como&nbsp;argumento</tt></dd></dl>\n",
" <dl><dt><a name=\"-numerPar\"><strong>numerPar</strong></a>()</dt><dd><tt>Función&nbsp;que&nbsp;devuelve&nbsp;los&nbsp;números&nbsp;pares&nbsp;de&nbsp;una&nbsp;lista&nbsp;que&nbsp;el&nbsp;usuario&nbsp;pase&nbsp;como&nbsp;argumento</tt></dd></dl>\n",
"</td></tr></table>\n",
"</body></html>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from IPython.display import HTML\n",
"HTML(filename=\"miModulo/tarea2_ejercicios1.html\")"
]
}
],
"metadata": {
......@@ -1384,4 +1452,3 @@
"nbformat": 4,
"nbformat_minor": 2
}
......@@ -12,13 +12,13 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 39,
"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": 5,
"execution_count": 40,
"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": 6,
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 6,
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Maxi = Dog(\"Maxi\")\n",
"Maxi.get_kind()\n"
"Max = Dog(\"Max\")\n",
"Max.get_kind()\n",
"Max._Dog__kind"
]
},
{
......@@ -232,11 +233,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",
......@@ -245,28 +249,28 @@
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 59,
"execution_count": 41,
"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 #Get\n",
" def age(self):\n",
" return self.__age\n",
" @age.setter #Set\n",
" def age(self, value):\n",
" self.__age = value\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",
" @staticmethod #Solo bark es staticmethod\n",
" def bark(times):\n",
" print(\"Guau \"*times)\n",
" def __str__(self):\n",
......@@ -277,34 +281,34 @@
},
{
"cell_type": "code",
"execution_count": 60,
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Guau Guau Guau \n"
"Guau Guau Guau Guau Guau Guau Guau Guau Guau Guau \n"
]
}
],
"source": [
"Dog.bark(3)\n",
"Dog.bark(10)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 61,
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Canis Lupus'"
"'Canis Lopus'"
]
},
"execution_count": 61,
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
......@@ -313,6 +317,26 @@
"Dog.get_kind()"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Max a muerto\n",
"1\n"
]
}
],
"source": [
"Max = Dog(\"Max\")\n",
"Max.age+=1\n",
"print(Max.age)"
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -322,48 +346,49 @@
},
{
"cell_type": "code",
"execution_count": 62,
"execution_count": 43,
"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": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Canis Lupus\n",
"Max\n",
"Canis Lopus\n",
"Maximus\n",
"[]\n"
]
}
],
"source": [
"max = Malinois(\"Max\")\n",
"print(max.get_kind())\n",
"print(max.name)\n",
"print(max.tricks)"
"Maximus = Malinois(\"Maximus\")\n",
"print(Max.get_kind())\n",
"print(Max.name)\n",
"print(Max.tricks)"
]
},
{
"cell_type": "code",
"execution_count": 66,
"execution_count": 47,
"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",
......@@ -374,37 +399,126 @@
},
{
"cell_type": "code",
"execution_count": 67,
"execution_count": 48,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Canis Lupus\n",
"Max\n",
"Canis Lopus\n",
"Keeper\n",
"['Fetch']\n",
"Max es un Canis Lupus de raza Malinois\n",
"Max a muerto\n"
"Keeper es un Canis Lopus de raza Malinois\n",
"Keeper 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)"
"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": 50,
"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": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'name': 'Frida', 'tricks': ['fetch'], 'section': 'K9', '_Dog__age': 0}\n",
"K9\n",
"Frida es un Canis Lopus Policia de raza Malinois con uniforme Azul\n"
]
}
],
"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": [
"## 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,
......@@ -418,7 +532,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",
......@@ -434,29 +548,121 @@
"\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."
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 117,
"metadata": {},
"outputs": [],
"source": []
"source": [
"from datetime import datetime\n",
"\n",
"class Nota:\n",
" def __init__(self,text,section,author,title,date=datetime.today(),source=None):\n",
" self.text=text\n",
" self.section=section\n",
" self.author=author\n",
" self.date=date\n",
" self.title=title\n",
" self.source=source\n",
" \n",
" def __str__(self):\n",
" out=\"\"\n",
" out+=self.title+\"\\t\"+self.date.strftime(\"%m-%d-%y\")+\"\\n\"\n",
" out+=self.author+\"\\n\"\n",
" out+=\"Sección: \"+self.section+\"\\n\"\n",
" if self.source.nombre is not None:\n",
" out+=self.source.nombre+\"\\n\"\n",
" out+=\"\\n\"+self.text\n",
" return out\n",
" \n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 118,
"metadata": {},
"outputs": [],
"source": []
"source": [
"miNota=Nota(\"Este es el contenido de la nota\",\"Investigacion\",\"CGarcia\",\"Titulo de la nota\")\n",
"Editorial=Fuente(\"La Jornada\", \"http://jornada.unam.mx\")\n",
"miNota.source=Editorial"
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Titulo de la nota\t02-05-19\n",
"CGarcia\n",
"Sección: Investigacion\n",
"La Jornada\n",
"\n",
"Este es el contenido de la nota\n"
]
}
],
"source": [
"print(miNota)"
]
},
{
"cell_type": "code",
"execution_count": 116,
"metadata": {},
"outputs": [],
"source": [
"class Fuente:\n",
" def __init__(self,nombre,url):\n",
" self.nombre=nombre\n",
" self.url=url\n",
" \n",
" def __str__(self):\n",
" return str(self.nombre)\n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": 120,
"metadata": {},
"outputs": [],
"source": [
"class Editor:\n",
" def __init__(self, topic):\n",
" self.topic=topic\n",
" \n",
" \n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": 122,
"metadata": {},
"outputs": [],
"source": [
"class Editorial:\n",
" pass"
]
}
],
"metadata": {
......
......@@ -4,15 +4,670 @@
"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": "code",
"execution_count": null,
"execution_count": 208,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n"
]
}
],
"source": [
"#lista para los ejercicios\n",
"lista=[]\n",
"for i in range(11):\n",
" lista.append(i)\n",
" \n",
"print(lista)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.1 Obten el promedio de los numeros en una lista."
]
},
{
"cell_type": "code",
"execution_count": 210,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"12.5\n",
"5.0\n"
]
}
],
"source": [
"def ejercicio1(lista):\n",
" suma=0\n",
" div=None\n",
" for num in lista:\n",
" suma+=num\n",
" div=(suma/len(lista))\n",
" print(div)\n",
"\n",
"ejercicio1([5,10,15,20])\n",
"ejercicio1(lista)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.2 Regresa todos los numeros enteros en una lista dividida por un numero."
]
},
{
"cell_type": "code",
"execution_count": 211,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{0, 1, 2, 3}\n"
]
}
],
"source": [
"def ejercicio2(lista, numero):\n",
" listaEnt=[x//numero for x in lista]\n",
" setEnt=set(listaEnt)\n",
" print(setEnt)\n",
" \n",
"ejercicio2(lista,3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.3 Encuentra el factorial de un numero usando recursion.\n"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"120"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def ejercicio3(numero):\n",
" if numero == 1:\n",
" return numero\n",
" else:\n",
" return numero*ejercicio3(numero-1)\n",
"\n",
"ejercicio3(5)"
]
},
{
"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": 206,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"Es palindromo\n",
"2\n",
"Es palindromo\n",
"3\n",
"Es palindromo\n",
"4\n",
"Es palindromo\n",
"5\n",
"Es palindromo\n",
"6\n",
"Es palindromo\n",
"7\n",
"Es palindromo\n",
"8\n",
"Es palindromo\n",
"9\n",
"Es palindromo\n",
"10\n",
"No es palindromo\n",
"11\n",
"Es palindromo\n",
"12\n",
"No es palindromo\n",
"13\n",
"No es palindromo\n",
"14\n",
"No es palindromo\n",
"15\n",
"No es palindromo\n",
"16\n",
"No es palindromo\n",
"17\n",
"No es palindromo\n",
"18\n",
"No es palindromo\n",
"19\n",
"No es palindromo\n",
"20\n",
"No es palindromo\n",
"21\n",
"No es palindromo\n",
"22\n",
"Es palindromo\n",
"23\n",
"No es palindromo\n",
"24\n",
"No es palindromo\n",
"25\n",
"No es palindromo\n",
"26\n",
"No es palindromo\n",
"27\n",
"No es palindromo\n",
"28\n",
"No es palindromo\n",
"29\n",
"No es palindromo\n",
"30\n",
"No es palindromo\n",
"31\n",
"No es palindromo\n",
"32\n",
"No es palindromo\n",
"33\n",
"Es palindromo\n",
"34\n",
"No es palindromo\n",
"35\n",
"No es palindromo\n",
"36\n",
"No es palindromo\n",
"37\n",
"No es palindromo\n",
"38\n",
"No es palindromo\n",
"39\n",
"No es palindromo\n",
"40\n",
"No es palindromo\n",
"41\n",
"No es palindromo\n",
"42\n",
"No es palindromo\n",
"43\n",
"No es palindromo\n",
"44\n",
"Es palindromo\n",
"45\n",
"No es palindromo\n",
"46\n",
"No es palindromo\n",
"47\n",
"No es palindromo\n",
"48\n",
"No es palindromo\n",
"49\n",
"No es palindromo\n",
"50\n",
"No es palindromo\n",
"51\n",
"No es palindromo\n",
"52\n",
"No es palindromo\n",
"53\n",
"No es palindromo\n",
"54\n",
"No es palindromo\n",
"55\n",
"Es palindromo\n",
"56\n",
"No es palindromo\n",
"57\n",
"No es palindromo\n",
"58\n",
"No es palindromo\n",
"59\n",
"No es palindromo\n",
"60\n",
"No es palindromo\n",
"61\n",
"No es palindromo\n",
"62\n",
"No es palindromo\n",
"63\n",
"No es palindromo\n",
"64\n",
"No es palindromo\n",
"65\n",
"No es palindromo\n",
"66\n",
"Es palindromo\n",
"67\n",
"No es palindromo\n",
"68\n",
"No es palindromo\n",
"69\n",
"No es palindromo\n",
"70\n",
"No es palindromo\n",
"71\n",
"No es palindromo\n",
"72\n",
"No es palindromo\n",
"73\n",
"No es palindromo\n",
"74\n",
"No es palindromo\n",
"75\n",
"No es palindromo\n",
"76\n",
"No es palindromo\n",
"77\n",
"Es palindromo\n",
"78\n",
"No es palindromo\n",
"79\n",
"No es palindromo\n",
"80\n",
"No es palindromo\n",
"81\n",
"No es palindromo\n",
"82\n",
"No es palindromo\n",
"83\n",
"No es palindromo\n",
"84\n",
"No es palindromo\n",
"85\n",
"No es palindromo\n",
"86\n",
"No es palindromo\n",
"87\n",
"No es palindromo\n",
"88\n",
"Es palindromo\n",
"89\n",
"No es palindromo\n",
"90\n",
"No es palindromo\n",
"91\n",
"No es palindromo\n",
"92\n",
"No es palindromo\n",
"93\n",
"No es palindromo\n",
"94\n",
"No es palindromo\n",
"95\n",
"No es palindromo\n",
"96\n",
"No es palindromo\n",
"97\n",
"No es palindromo\n",
"98\n",
"No es palindromo\n",
"99\n",
"Es palindromo\n",
"100\n",
"No es palindromo\n",
"101\n",
"Es palindromo\n",
"Lista de palindromos: \n",
"\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101]\n",
"Lista de palindromos e impares: \n",
"\n",
"[1, 3, 5, 7, 9, 11, 33, 55, 77, 99, 101]\n"
]
}
],
"source": [
"listaejem=[]\n",
"\n",
"def ejercicio4(minimo, maximo):\n",
" for i in range(minimo,maximo):\n",
" print(i)\n",
" aux=i\n",
" rev=0\n",
" while(i>0):\n",
" digito=i%10\n",
" rev=rev*10+digito\n",
" i=i//10\n",
" if(aux==rev):\n",
" listaejem.append(aux)\n",
" print(\"Es palindromo\")\n",
" else:\n",
" print(\"No es palindromo\")\n",
" \n",
" print(\"Lista de palindromos: \\n\")\n",
" print(listaejem)\n",
" \n",
" imparlista=[impar for impar in listaejem if impar%2==1]\n",
" print(\"Lista de palindromos e impares: \\n\")\n",
" print(imparlista)\n",
"\n",
"ejercicio4(1,102)"
]
},
{
"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": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dime una palabra: hola\n",
"['_', '_', '_', '_']\n",
"Dame una letra: q\n",
"\n",
"te quedan 1 intentos!\n",
"\n",
"['_', '_', '_', '_']\n",
"Dame una letra: q\n",
"\n",
"te quedan 0 intentos!\n",
"\n",
"Ya perdiste! -_-\n",
" la palabra era: \n",
"['h', 'o', 'l', 'a']\n"
]
}
],
"source": [
"def ejercicio5(intentos=2):\n",
" palabra = ''\n",
" listaPalabra = []\n",
" listaPalabraEspacio = []\n",
" letra = ''\n",
" detente= 1\n",
" \n",
" palabra= str(input('Dime una palabra: '))\n",
" palabra=palabra.lower()\n",
" listaPalabra=list(palabra)\n",
" for palabr in listaPalabra:\n",
" listaPalabraEspacio.append('_')\n",
" \n",
" while detente==1:\n",
" print(listaPalabraEspacio)\n",
" letra = input('Dame una letra: ')\n",
" fallo = False\n",
" if letra not in listaPalabra:\n",
" fallo = True\n",
" intentos=intentos-1\n",
" print(\"\\nte quedan \"+ str(intentos)+\" intentos!\\n\")\n",
" \n",
" else: \n",
" for key, value in enumerate(listaPalabra):\n",
" if value == letra:\n",
" listaPalabraEspacio[key] = value\n",
" \n",
" if intentos <= 0:\n",
" detente= 0\n",
" print(\"Ya perdiste! -_-\\n la palabra era: \\n\"+ str(listaPalabra))\n",
" elif listaPalabra == listaPalabraEspacio:\n",
" detente= 0 \n",
" print(\"Ya ganaste! ͡° ͜ʖ ͡° \\n la palabra era \\n\"+str(listaPalabra))\n",
" \n",
"ejercicio5()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.6 Escribe una funcion que reciba un texto y regrese un diccionario ordenado con el numero de ocurrencias de cada palabra en el texto."
]
},
{
"cell_type": "code",
"execution_count": 201,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Escriba su texto: \n",
"hola mundo infeliz hola\n",
"['hola', 'mundo', 'infeliz', 'hola']\n",
"{'hola': 2, 'mundo': 1, 'infeliz': 1}\n"
]
}
],
"source": [
"dicti={}\n",
"\n",
"def ejercicio6():\n",
" texto=str(input(\"Escriba su texto: \\n\"))\n",
" texto=texto.split()\n",
" print(texto)\n",
" for palabra in texto:\n",
" dicti.update({palabra:texto.count(palabra)})\n",
" print(dicti)\n",
" \n",
"ejercicio6()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.7 Escribe una clase que convierta un numero entero a numero romano."
]
},
{
"cell_type": "code",
"execution_count": 319,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ingresar número (Cero para terminar el programa):10\n",
"10:\n",
"X\n",
"Ingresar número (Cero para terminar el programa):24\n",
"24:\n",
"XXIV\n",
"Ingresar número (Cero para terminar el programa):0\n"
]
}
],
"source": [
"enteros= [1000, 900, 500, 400,100, 90, 50, 40,10, 9, 5, 4,1] \n",
"Letras = [\"M\", \"CM\", \"D\", \"CD\",\"C\", \"XC\", \"L\", \"XL\",\"X\", \"IX\", \"V\", \"IV\",\"I\"]\n",
"romano=\"\"\n",
"while True:\n",
" x=int(input(\"Ingresar número (Cero para terminar el programa):\"))\n",
" if(x==0):\n",
" break\n",
" print(str(x)+\":\")\n",
" i=0\n",
" \n",
" while (x>0):\n",
" if(x>=enteros[i]):\n",
" x=x-enteros[i]\n",
" romano+=Letras[i]\n",
" else:\n",
" i=i+1\n",
" print(romano)\n",
" romano=\"\""
]
},
{
"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": 278,
"metadata": {},
"outputs": [],
"source": []
"source": [
"import numpy as np\n",
"import random as rnd"
]
},
{
"cell_type": "code",
"execution_count": 318,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ingresa el tamaño del cuadrado: \n",
"3\n",
"[[0. 0. 0.]\n",
" [0. 0. 0.]\n",
" [0. 0. 0.]]\n",
"-----\n",
"soy j:1\n",
"[[0. 1. 0.]\n",
" [0. 0. 0.]\n",
" [0. 0. 0.]]\n",
"-----\n",
"soy j:2\n",
"[[0. 1. 0.]\n",
" [0. 0. 0.]\n",
" [0. 0. 2.]]\n",
"-----\n",
"soy j:0\n",
"1.0\n",
"La celda esta ocupada, regresa e inserta abajo\n",
"[[0. 1. 0.]\n",
" [3. 0. 0.]\n",
" [0. 0. 2.]]\n",
"-----\n",
"soy j:0\n",
"[[0. 1. 0.]\n",
" [3. 0. 0.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:1\n",
"[[0. 1. 0.]\n",
" [3. 5. 0.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:2\n",
"4.0\n",
"La celda esta ocupada, regresa e inserta abajo\n",
"[[0. 1. 6.]\n",
" [3. 5. 0.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:2\n",
"[[0. 1. 6.]\n",
" [3. 5. 7.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:0\n",
"[[8. 1. 6.]\n",
" [3. 5. 7.]\n",
" [4. 0. 2.]]\n",
"-----\n",
"soy j:1\n",
"7.0\n",
"La celda esta ocupada, regresa e inserta abajo\n",
"[[8. 1. 6.]\n",
" [3. 5. 7.]\n",
" [4. 9. 2.]]\n",
"-----\n",
"[[8. 1. 6.]\n",
" [3. 5. 7.]\n",
" [4. 9. 2.]]\n"
]
}
],
"source": [
"def ejercicio8():\n",
" tam=input(\"Ingresa el tamaño del cuadrado: \\n\")\n",
" tam=int(tam)\n",
" magico=np.zeros((tam,tam))\n",
" print(magico)\n",
" print(\"-----\")\n",
" if tam==2:\n",
" print(\"no hay solucion :v\")\n",
" \n",
" if tam%2==1:\n",
" #inicializacion\n",
" n = 1\n",
" i, j = 0, tam//2\n",
" \n",
" #numero de elementos\n",
" while n <= tam**2:\n",
" print(\"soy j:\"+str(j))\n",
" magico[i, j] = n\n",
" \n",
" #Siguiente movimiento\n",
" n += 1\n",
" movi, movj = (i-1) % tam, (j+1)% tam\n",
" \n",
" if magico[movi, movj]:\n",
" print(magico[movi,movj])\n",
" print(\"La celda esta ocupada, regresa e inserta abajo\")\n",
" i += 1\n",
" else:\n",
" i, j = movi, movj\n",
" \n",
" print(magico)\n",
" print(\"-----\")\n",
" \n",
" #pares mayores de dos \n",
" elif ((tam!=2) and (tam%2==0)):\n",
" print(\"no se hacerlo\")\n",
" \n",
" print(magico)\n",
"ejercicio8()"
]
}
],
"metadata": {
......@@ -31,7 +686,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8rc1"
"version": "3.5.2"
}
},
"nbformat": 4,
......
{
"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
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: module tarea2_ejercicios1</title>
<meta charset="utf-8">
</head><body bgcolor="#f0f0f8">
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="#7799ee">
<td valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong>tarea2_ejercicios1</strong></big></big></font></td
><td align=right valign=bottom
><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:/home/carlosgarcia8/repos/tap1012/miModulo/tarea2_ejercicios1.py">/home/carlosgarcia8/repos/tap1012/miModulo/tarea2_ejercicios1.py</a></font></td></tr></table>
<p><tt>Documentación&nbsp;para&nbsp;la&nbsp;segunda&nbsp;tarea&nbsp;(ejercicios&nbsp;1)&nbsp;de&nbsp;la&nbsp;materia&nbsp;de&nbsp;Tópicos&nbsp;Avanzados&nbsp;de&nbsp;Programación.<br>
Maestría&nbsp;GeoInteligencia&nbsp;Computacional&nbsp;a&nbsp;27&nbsp;de&nbsp;Enero&nbsp;del&nbsp;2019.</tt></p>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#eeaa77">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><dl><dt><a name="-coincide"><strong>coincide</strong></a>(l1, l2)</dt><dd><tt>Función&nbsp;que&nbsp;devuelve&nbsp;todos&nbsp;los&nbsp;elementos&nbsp;coincidentes&nbsp;de&nbsp;un&nbsp;par&nbsp;de&nbsp;listas&nbsp;que&nbsp;el&nbsp;usuario&nbsp;pase&nbsp;como&nbsp;argumento</tt></dd></dl>
<dl><dt><a name="-numerMay"><strong>numerMay</strong></a>(l1)</dt><dd><tt>Función&nbsp;que&nbsp;devuelve&nbsp;los&nbsp;números&nbsp;estrictamente&nbsp;mayores&nbsp;a&nbsp;10&nbsp;de&nbsp;una&nbsp;lista&nbsp;que&nbsp;el&nbsp;usuario&nbsp;pase&nbsp;como&nbsp;argumento</tt></dd></dl>
<dl><dt><a name="-numerPar"><strong>numerPar</strong></a>()</dt><dd><tt>Función&nbsp;que&nbsp;devuelve&nbsp;los&nbsp;números&nbsp;pares&nbsp;de&nbsp;una&nbsp;lista&nbsp;que&nbsp;el&nbsp;usuario&nbsp;pase&nbsp;como&nbsp;argumento</tt></dd></dl>
</td></tr></table>
</body></html>
\ No newline at end of file
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Documentación para la segunda tarea (ejercicios 1) de la materia de Tópicos Avanzados de Programación.
Maestría GeoInteligencia Computacional a 27 de Enero del 2019.
"""
def numerPar():
'''
Función que devuelve los números pares de una lista que el usuario pase como argumento
'''
lista=[x for x in range(0,21) if x%2==0]
return lista
def numerMay(l1):
'''
Función que devuelve los números estrictamente mayores a 10 de una lista que el usuario pase como argumento
'''
lista=[x for x in l1 if x>10]
return lista
def coincide(l1,l2):
'''
Función que devuelve todos los elementos coincidentes de un par de listas que el usuario pase como argumento
'''
coin=set([x for x in l1 if x in l2])
return coin
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