diff --git a/03 - Flujos de Control/Mi_TareaResuelta.ipynb b/03 - Flujos de Control/Mi_TareaResuelta.ipynb new file mode 100644 index 000000000..be84df32b --- /dev/null +++ b/03 - Flujos de Control/Mi_TareaResuelta.ipynb @@ -0,0 +1,382 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1) Crear una variable que contenga un elemento del conjunto de números enteros y luego imprimir por pantalla si es mayor o menor a cero" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "a = -2\n", + "if a > 0:\n", + " print(\"a es mayor a cero\")\n", + "else:\n", + " print(\"es menor a cero\")" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2) Crear dos variables y un condicional que informe si son del mismo tipo de dato\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "a = 10\n", + "b = \"10\"\n", + "if type(a)==type(b):\n", + " print(\"a y b son del mismo tipo\")\n", + "else:\n", + " print(\"Son de diferente tipo\")\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "3) Para los valores enteros del 1 al 20, imprimir por pantalla si es par o impar\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for i in range(1,21):\n", + " if i%2==0:\n", + " print(\"El \",i,\" es par\")\n", + " else:\n", + " print(\"El \",i,\" es impar\")\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "4) En un ciclo for mostrar para los valores entre 0 y 5 el resultado de elevarlo a la potencia igual a 3\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for num in range(0,6):\n", + " print(num,\" elevado a la tercera potencia es: \",num**3)\n", + "\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "5) Crear una variable que contenga un número entero y realizar un ciclo for la misma cantidad de ciclos\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "x = 6\n", + "for rep in range(x):\n", + " print(\"Esta es la repetición: \", rep)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "6) Utilizar un ciclo while para realizar el factorial de un número guardado en una variable, sólo si la variable contiene un número entero mayor a 0\n" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "120\n" + ] + } + ], + "source": [ + "num = 5\n", + "factorial = 1\n", + "if (num > 0):\n", + " factorial = num\n", + " while (num > 2):\n", + " num -=1\n", + " factorial = num*factorial\n", + " print(factorial)\n", + "else:\n", + " print(\"La variable no es mayor a cero\")\n", + " \n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "7) Crear un ciclo for dentro de un ciclo while\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "y = 0\n", + "while y < 5:\n", + " for i in range(1,y):\n", + " print(\"For\", i)\n", + " print(\"While\", y)\n", + " y+=1\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "8) Crear un ciclo while dentro de un ciclo for\n" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [], + "source": [ + "n = 4\n", + "for i in range(1,n):\n", + " while (n < 4):\n", + " n -= 1\n", + " print(\"while\",n)\n", + " print(\"for\",i)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "9) Imprimir los números primos existentes entre 0 y 30\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "el numero 2 es primo\n", + "el numero 3 es primo\n", + "el numero 5 es primo\n", + "el numero 7 es primo\n", + "el numero 11 es primo\n", + "el numero 13 es primo\n", + "el numero 17 es primo\n", + "el numero 19 es primo\n", + "el numero 23 es primo\n", + "el numero 29 es primo\n" + ] + } + ], + "source": [ + "n=2\n", + "fin = 30\n", + "\n", + "while n <= fin:\n", + " primo = True\n", + " for i in range(2,n):\n", + " modulo = n%i\n", + " if modulo == 0:\n", + " primo= False\n", + " \n", + " if primo:\n", + " print(f\"el numero {n} es primo\")\n", + " n+=1\n", + " \n", + "\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "10) ¿Se puede mejorar el proceso del punto 9? Utilizar las sentencias break y/ó continue para tal fin\n", + "11) mirar qué tanto se optimizó" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "n=2\n", + "fin = 30\n", + "ciclos_sin = 0 #contar el número de ciclos\n", + "while n <= fin:\n", + " primo = True\n", + " for i in range(2,n):\n", + " ciclos_sin += 1\n", + " modulo = n%i\n", + " if modulo == 0:\n", + " primo= False\n", + " break \n", + " if primo:\n", + " print(f\"el numero {n} es primo\")\n", + " n+=1\n", + "print(f\"Los ciclos sin break fueron: {ciclos_sin}\")" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "13) Aplicando continue, armar un ciclo while que solo imprima los valores divisibles por 12, dentro del rango de números de 100 a 300\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "n=99\n", + "f=300\n", + "while (n<=300):\n", + " n+=1\n", + " if n%12 != 0:\n", + " continue\n", + " else:\n", + " print(n)\n", + "\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "14) Utilizar la función **input()** que permite hacer ingresos por teclado, para encontrar números primos y dar la opción al usario de buscar el siguiente" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "n=2\n", + "primo = True\n", + "buscar_primo = True\n", + "\n", + "while buscar_primo: \n", + " for i in range(2,n):\n", + " modulo = n%i\n", + " if modulo == 0:\n", + " primo= False\n", + " break\n", + " if primo:\n", + " print(f\"el numero {n} es primo\")\n", + " print(\"Desea encontrar el siguien? \")\n", + " continuar = input(\"ingrese si o no: \")\n", + " if continuar != 'si':\n", + " print(\"se finaliza la búsqueda\")\n", + " buscar_primo = False\n", + " break\n", + " else:\n", + " primo = True\n", + " n+=1" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "15) Crear un ciclo while que encuentre dentro del rango de 100 a 300 el primer número divisible por 3 y además múltiplo de 6" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "102\n" + ] + } + ], + "source": [ + "n = 99\n", + "fin = 300\n", + "while(n<=fin):\n", + " n+=1\n", + " if n%3 == 0 and n%6 == 0:\n", + " print(n)\n", + " break\n", + " else:\n", + " continue" + ] + } + ], + "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.11.4" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/04 - Estructuras de datos/Mi_TareaResuelta.ipynb b/04 - Estructuras de datos/Mi_TareaResuelta.ipynb new file mode 100644 index 000000000..8d345a70b --- /dev/null +++ b/04 - Estructuras de datos/Mi_TareaResuelta.ipynb @@ -0,0 +1,627 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "1) Crear una lista que contenga nombres de ciudades del mundo que contenga más de 5 elementos e imprimir por pantalla\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Cali', 'Bogota', 'Palmira', 'Roma', 'Capurgana', 'Londres']\n" + ] + } + ], + "source": [ + "towns = [\"Cali\", \"Bogota\", \"Palmira\", \"Roma\", \"Capurgana\", \"Londres\"]\n", + "print(towns)\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2) Imprimir por pantalla el segundo elemento de la lista\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Bogota\n" + ] + } + ], + "source": [ + "print(towns[1])" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "3) Imprimir por pantalla del segundo al cuarto elemento\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Bogota', 'Palmira', 'Roma', 'Capurgana']\n" + ] + } + ], + "source": [ + "print(towns[1:5])" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "4) Visualizar el tipo de dato de la lista\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "list" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(towns)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "5) Visualizar todos los elementos de la lista a partir del tercero de manera genérica, es decir, sin explicitar la posición del último elemento\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Palmira', 'Roma', 'Capurgana', 'Londres']\n" + ] + } + ], + "source": [ + "print(towns[2:])" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "6) Visualizar los primeros 4 elementos de la lista\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Cali', 'Bogota', 'Palmira', 'Roma']\n" + ] + } + ], + "source": [ + "print(towns[:4])" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "7) Agregar una ciudad más a la lista que ya exista y otra que no ¿Arroja algún tipo de error?\n" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Cali', 'Bogota', 'Palmira', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira']\n" + ] + } + ], + "source": [ + "towns.append(\"Medellin\")\n", + "towns.append(\"Palmira\")\n", + "print(towns)\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "8) Agregar otra ciudad, pero en la cuarta posición\n" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Cali', 'Bogota', 'Palmira', 'Barranquilla', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira']\n" + ] + } + ], + "source": [ + "towns.insert(3,\"Barranquilla\")\n", + "print(towns)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "9) Concatenar otra lista a la ya creada\n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Cali', 'Bogota', 'Palmira', 'Barranquilla', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira', 'Madrid', 'Berlin', 'Boston']\n" + ] + } + ], + "source": [ + "towns.extend([\"Madrid\", \"Berlin\", \"Boston\"])\n", + "print(towns)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "10) Encontrar el índice de la ciudad que en el punto 7 agregamos duplicada. ¿Se nota alguna particularidad?\n" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n" + ] + } + ], + "source": [ + "print(towns.index(\"Palmira\"))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "12) Eliminar un elemento de la lista\n" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Cali', 'Bogota', 'Barranquilla', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira', 'Madrid', 'Berlin', 'Boston']\n" + ] + } + ], + "source": [ + "towns.remove(\"Palmira\")\n", + "print(towns)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "14) Extraer el úlimo elemento de la lista, guardarlo en una variable e imprimirlo\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Boston\n" + ] + } + ], + "source": [ + "ultimo = towns.pop()\n", + "print(ultimo)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "15) Mostrar la lista multiplicada por 4\n" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Cali', 'Bogota', 'Barranquilla', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira', 'Madrid', 'Berlin', 'Cali', 'Bogota', 'Barranquilla', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira', 'Madrid', 'Berlin', 'Cali', 'Bogota', 'Barranquilla', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira', 'Madrid', 'Berlin', 'Cali', 'Bogota', 'Barranquilla', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira', 'Madrid', 'Berlin']\n" + ] + } + ], + "source": [ + "print(towns*4)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "16) Crear una tupla que contenga los números enteros del 1 al 20\n" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "num = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "17) Imprimir desde el índice 10 al 15 de la tupla\n" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(11, 12, 13, 14, 15, 16)\n" + ] + } + ], + "source": [ + "print(num[10:16])" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "18) Evaluar si los números 20 y 30 están dentro de la tupla\n" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n" + ] + } + ], + "source": [ + "print(20 in num)\n", + "print(30 in num)\n", + "\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "19) Con la lista creada en el punto 1, validar la existencia del elemento 'París' y si no existe, agregarlo. Utilizar una variable e informar lo sucedido.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Se ha agregado exitosamente Paris, ya que no estaba en la lista\n" + ] + } + ], + "source": [ + "elemento = \"Paris\"\n", + "if (not(elemento in towns)):\n", + " towns.append(elemento)\n", + " print(\"Se ha agregado exitosamente Paris, ya que no estaba en la lista\")\n", + "else:\n", + " print(\"No fue necesario agregarlos\")\n", + " " + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "20) Mostrar la cantidad de veces que se encuentra un elemento específico dentro de la tupla y de la lista\n" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "1\n" + ] + } + ], + "source": [ + "print(towns.count(\"Palmira\"))\n", + "print(num.count(7))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "21) Convertir la tupla en una lista\n" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "list" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lista_new = list(num)\n", + "type(lista_new)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "22) Desempaquetar solo los primeros 3 elementos de la tupla en 3 variables\n" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3\n" + ] + } + ], + "source": [ + "uno,dos,tres,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_, = num\n", + "print(uno, dos, tres)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "23) Crear un diccionario utilizando la lista crada en el punto 1, asignandole la clave \"ciudad\". Agregar tambien otras claves, como puede ser \"Pais\" y \"Continente\".\n" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'ciudad': ['Cali', 'Bogota', 'Barranquilla', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira', 'Madrid', 'Berlin', 'Paris'], 'Pais': ['Argentina', 'Brasil', 'Colombia', 'Bolivia'], 'Continente': ['America', 'Europa', 'Africa', 'Asia']}\n" + ] + } + ], + "source": [ + "diccionario = {\"ciudad\":towns, \"Pais\":[\"Argentina\", \"Brasil\", \"Colombia\", \"Bolivia\"], \"Continente\":[\"America\", \"Europa\", \"Africa\", \"Asia\"]}\n", + "print(diccionario)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "24) Imprimir las claves del diccionario\n" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['ciudad', 'Pais', 'Continente'])" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "diccionario.keys()\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "25) Imprimir las ciudades a través de su clave\n" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_values([['Cali', 'Bogota', 'Barranquilla', 'Roma', 'Capurgana', 'Londres', 'Medellin', 'Palmira', 'Madrid', 'Berlin', 'Paris'], ['Argentina', 'Brasil', 'Colombia', 'Bolivia'], ['America', 'Europa', 'Africa', 'Asia']])" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "diccionario.values()" + ] + } + ], + "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.11.4" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/05 - Iteradores e Iterables/miTarea.ipynb b/05 - Iteradores e Iterables/miTarea.ipynb new file mode 100644 index 000000000..1362b3012 --- /dev/null +++ b/05 - Iteradores e Iterables/miTarea.ipynb @@ -0,0 +1,529 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1) A partir de una lista vacía, utilizar un ciclo while para cargar allí números negativos del -15 al -1\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[-15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1]\n" + ] + } + ], + "source": [ + "negativos = []\n", + "i = -15\n", + "fin = -1\n", + "while i <= fin:\n", + " negativos.append(i)\n", + " i+=1\n", + "print(negativos)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2) ¿Con un ciclo while sería posible recorrer la lista para imprimir sólo los números pares?\n" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "-14\n", + "-12\n", + "-10\n", + "-8\n", + "-6\n", + "-4\n", + "-2\n" + ] + } + ], + "source": [ + "n=0\n", + "while (n\n", + "n0 = 0
\n", + "n1 = 1
\n", + "ni = ni-1 + ni-2
\n", + "Crear una lista con los primeros treinta números de la sucesión.
" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229]\n" + ] + } + ], + "source": [ + "fibo= [0,1]\n", + "n =2 \n", + "while n<30:\n", + " fibo.append(fibo[n-1]+fibo[n-2])\n", + " n+=1\n", + "print(fibo)\n", + "\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "8) Realizar la suma de todos elementos de la lista del punto anterior" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1346268" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sum(fibo)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "9) La proporción aurea se expresa con una proporción matemática que nace el número irracional Phi= 1,618… que los griegos llamaron número áureo. El cuál se puede aproximar con la sucesión de Fibonacci. Con la lista del ejercicio anterior, imprimir el cociente de los últimos 5 pares de dos números contiguos:
\n", + "Donde i es la cantidad total de elementos
\n", + "ni-1 / ni
\n", + "ni-2 / ni-1
\n", + "ni-3 / ni-2
\n", + "ni-4 / ni-3
\n", + "ni-5 / ni-4
" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1.6180339887543225\n", + "1.618033988738303\n", + "1.6180339887802426\n", + "1.6180339886704431\n", + "1.618033988957902\n" + ] + } + ], + "source": [ + "n = len(fibo) - 1\n", + "ultimo = n - 5\n", + "while n > ultimo:\n", + " cociente = fibo[n]/fibo[n-1]\n", + " print(cociente)\n", + " n -=1" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "10) A partir de la variable cadena ya dada, mostrar en qué posiciones aparece la letra \"n\"
\n", + "cadena = 'Hola Mundo. Esto es una practica del lenguaje de programación Python'" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "7 n\n", + "21 n\n", + "39 n\n", + "60 n\n", + "67 n\n" + ] + } + ], + "source": [ + "cadena = 'Hola Mundo. Esto es una practica del lenguaje de programación Python'\n", + "for i,c in enumerate(cadena):\n", + " if c ==\"n\":\n", + " print(i,c)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "11) Crear un diccionario e imprimir sus claves utilizando un iterador" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "valle\n", + "antioquia\n", + "putumayo\n" + ] + } + ], + "source": [ + "dicc = {\"valle\":\"cali\", \"antioquia\":\"medellin\", \"putumayo\":\"mocoa\"}\n", + "for i in dicc:\n", + " print(i)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "12) Convertir en una lista la variable \"cadena\" del punto 10 y luego recorrerla con un iterador \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "cadena = list(cadena)\n", + "for c in cadena:\n", + " print(c)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "13) Crear dos listas y unirlas en una tupla utilizando la función zip\n" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "[('hi', 'robert'), ('eres', 'un'), ('modo', 'foka')]\n" + ] + } + ], + "source": [ + "lista1 = [\"hi\", \"eres\", \"modo\"]\n", + "lista2 = [\"robert\", \"un\", \"foka\"]\n", + "tuplazip = zip(lista1, lista2)\n", + "print(type(tuplazip))\n", + "print(list(tuplazip))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "14) A partir de la siguiente lista de números, crear una nueva sólo si el número es divisible por 7
\n", + "lis = [18,21,29,32,35,42,56,60,63,71,84,90,91,100]" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[21, 35, 42, 56, 63, 84, 91]\n" + ] + } + ], + "source": [ + "lis = [18,21,29,32,35,42,56,60,63,71,84,90,91,100]\n", + "lista7 = [i for i in lis if i%7 == 0]\n", + "print(lista7)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "15) A partir de la lista de a continuación, contar la cantidad total de elementos que contiene, teniendo en cuenta que un elemento de la lista podría ser otra lista:
\n", + "lis = [[1,2,3,4],'rojo','verde',[True,False,False],['uno','dos','tres']]" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "12\n" + ] + } + ], + "source": [ + "lis = [[1,2,3,4],'rojo','verde',[True,False,False],['uno','dos','tres']]\n", + "contador = 0\n", + "for i in lis: \n", + " if type(i) == list:\n", + " contador += len(i)\n", + " else:\n", + " contador += 1\n", + " \n", + "print(contador)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "16) Tomar la lista del punto anterior y convertir cada elemento en una lista si no lo es\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[1, 2, 3, 4], ['rojo'], ['verde'], [True, False, False], ['uno', 'dos', 'tres']]\n" + ] + } + ], + "source": [ + "for indice, elemento in enumerate(lis):\n", + " if (type(elemento) != list):\n", + " lis[indice]=[elemento]\n", + "print(lis)\n" + ] + } + ], + "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.11.4" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/06 - Funciones/MitareaResuelta.ipynb b/06 - Funciones/MitareaResuelta.ipynb new file mode 100644 index 000000000..c3a0ec99f --- /dev/null +++ b/06 - Funciones/MitareaResuelta.ipynb @@ -0,0 +1,357 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#EJEMPLO DE RECURSIVIDAD\n", + "def factorial(numero):\n", + " if (numero > 1):\n", + " numero = numero * factorial(numero - 1)\n", + " return numero" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#EJEMPLO FUNCION LAMBDA\n", + "lambda_producto = lambda x, y: x * y\n", + "lambda_producto(3, 4)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1) Crear una función que reciba un número como parámetro y devuelva si True si es primo y False si no lo es\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def primo(num):\n", + " pri = True\n", + " for i in range(2,num):\n", + " if num%i == 0:\n", + " pri = False\n", + " break\n", + " return pri\n", + "\n", + "primo(7)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2) Utilizando la función del punto 1, realizar otra función que reciba de parámetro una lista de números y devuelva sólo aquellos que son primos en otra lista" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 5, 7, 11, 13, 17, 19]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def extraer_primos(lista):\n", + " listaPrimos = []\n", + " for elemento in lista:\n", + " if primo(int(elemento)):\n", + " listaPrimos.append(elemento)\n", + " return listaPrimos\n", + "\n", + "lis_completa = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]\n", + "ListaDePris = extraer_primos(lis_completa)\n", + "ListaDePris\n", + "\n", + " " + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "3) Crear una función que al recibir una lista de números, devuelva el que más se repite y cuántas veces lo hace. Si hay más de un \"más repetido\", que devuelva cualquiera" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(5, 4)" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def masRepetido(lista):\n", + " contador = {} \n", + " for num in lista:\n", + " if num in contador.keys():\n", + " contador[num] += 1 \n", + " else:\n", + " contador[num] = 1\n", + " moda = None\n", + " maximo = 0\n", + " for numero, repeticion in contador.items():\n", + " if repeticion > maximo:\n", + " maximo = repeticion\n", + " moda = numero\n", + " return moda, maximo\n", + " \n", + "lis = [10,1,5,6,8,10,22,5,6,4,11,10,9,5,5]\n", + "masRepetido(lis)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "4)A la función del punto 3, agregar un parámetro más, que permita elegir si se requiere el menor o el mayor de los mas repetidos" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(5, 3)" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def masRepetido(lista, modo):\n", + " contador = {} \n", + " for num in lista:\n", + " if num in contador.keys():\n", + " contador[num] += 1 \n", + " else:\n", + " contador[num] = 1\n", + " moda = []\n", + " maximo = 0\n", + " for numero, repeticion in contador.items():\n", + " if repeticion > maximo:\n", + " maximo = repeticion\n", + " moda = [numero]\n", + " elif repeticion == maximo:\n", + " moda.append(numero)\n", + " if modo == 'menor':\n", + " masRepetido_num = min(moda)\n", + " elif modo == 'mayor':\n", + " masRepetido_num = max(moda)\n", + " return masRepetido_num, maximo\n", + "\n", + "\n", + "lis = [10,1,5,6,8,10,22,5,6,4,11,10,9,5]\n", + "masRepetido(lis, 'menor')" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "5)Crear una función que convierta entre grados Celsius, Farenheit y Kelvin\n", + "Fórmula 1 : (°C × 9/5) + 32 = °F\n", + "Fórmula 2 : °C + 273.15 = °K\n", + "Debe recibir 3 parámetros: el valor, la medida de orígen y la medida de destino" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "255.92777777777775\n" + ] + } + ], + "source": [ + "def conversor(valor,origen,destino):\n", + " if origen == 'celsius':\n", + " if destino == 'celsius':\n", + " valorDestino = valor\n", + " elif destino == 'farenheit':\n", + " valorDestino = (valor * 9/5) + 32\n", + " elif destino == 'kelvin':\n", + " valorDestino = valor + 273.15\n", + " else:\n", + " print(\"Parametro de destino no valido\")\n", + " elif origen == 'farenheit':\n", + " if destino == 'farenheit':\n", + " valorDestino = valor\n", + " elif destino == 'celsius':\n", + " valorDestino = ((valor - 32)*5) /9\n", + " elif destino == 'kelvin':\n", + " valorDestino = ((valor - 32)*5 /9) + 273.15\n", + " else:\n", + " print(\"Parametro de destino no valido\")\n", + " elif origen == 'kelvin':\n", + " if destino == 'kelvin':\n", + " valorDestino = valor\n", + " elif destino == 'farenheit':\n", + " valorDestino = (valor - 273.15) * (9/5) + 32\n", + " elif destino == 'celsius':\n", + " valorDestino = (valor - 273.15) \n", + " else:\n", + " print(\"Parametro de destino no valido\")\n", + " else:\n", + " print(\"parametro de origen no valido\")\n", + " return valorDestino\n", + "\n", + "x = conversor(1,'farenheit','kelvin')\n", + "print(x)\n", + "\n", + "\n", + "\n", + " " + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "6) Iterando una lista con los tres valores posibles de temperatura que recibe la función del punto 5, hacer un print para cada combinación de los mismos:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "20 grados celsius a celsius : 20\n", + "20 grados celsius a kelvin : 293.15\n", + "20 grados celsius a farenheit : 68.0\n", + "20 grados kelvin a celsius : -253.14999999999998\n", + "20 grados kelvin a kelvin : 20\n", + "20 grados kelvin a farenheit : -423.66999999999996\n", + "20 grados farenheit a celsius : -6.666666666666667\n", + "20 grados farenheit a kelvin : 266.4833333333333\n", + "20 grados farenheit a farenheit : 20\n" + ] + } + ], + "source": [ + "unidades = ['celsius','kelvin','farenheit']\n", + "temperatura = 20\n", + "for i in unidades:\n", + " for j in unidades:\n", + " conversion = conversor(temperatura,i,j)\n", + " print('20 grados',i, 'a', j,':', conversor(20, i, j))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "7)Armar una función que devuelva el factorial de un número. Tener en cuenta que el usuario puede equivocarse y enviar de parámetro un número no entero o negativo" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "120\n" + ] + } + ], + "source": [ + "def factorial(numero):\n", + " if(type(numero) != int):\n", + " return 'El numero debe ser un entero'\n", + " if(numero < 0):\n", + " return 'El numero debe ser pisitivo'\n", + " if (numero > 1):\n", + " numero = numero * factorial(numero - 1)\n", + " return numero\n", + "\n", + "print(factorial(5))" + ] + } + ], + "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.11.4" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/07 - Clases & OOP/MitareaPOO.ipynb b/07 - Clases & OOP/MitareaPOO.ipynb new file mode 100644 index 000000000..8ca5b6186 --- /dev/null +++ b/07 - Clases & OOP/MitareaPOO.ipynb @@ -0,0 +1,531 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1) Crear la clase vehículo que contenga los atributos:\n", + "Color\n", + "Si es moto, auto, camioneta ó camión\n", + "Cilindrada del motor" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [], + "source": [ + "class Vehiculo:\n", + " def __init__(self, color, tipo, cilindrada):\n", + " self.color = color\n", + " self.tipo = tipo\n", + " self.cilindrada = cilindrada\n", + " \n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A la clase Vehiculo creada en el punto 1, agregar los siguientes métodos:\n", + "Acelerar\n", + "Frenar\n", + "Doblar" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "class Vehiculo:\n", + " def __init__(self, color, tipo, cilindrada):\n", + " self.color = color\n", + " self.tipo = tipo\n", + " self.cilindrada = cilindrada\n", + " self.velocidad = 0\n", + " self.direccion = 0\n", + " \n", + " def Acelerar(self,vel):\n", + " self.velocidad += vel\n", + "\n", + " def Frenar(self,vel):\n", + " self.velocidad -= vel\n", + " \n", + " def Doblar(self, grados):\n", + " self.direccion += grados\n", + "\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "3) Instanciar 3 objetos de la clase vehículo y ejecutar sus métodos, probar luego el resultado\n", + "instanciar es crear un objeto de la clase o inicializarlo" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "v1 = Vehiculo(\"verde\", \"moto\", \"600\")\n", + "v2 = Vehiculo(\"naranja\", \"camion\", \"5000\")\n", + "v3 = Vehiculo(\"rojo\", \"carro\", \"2000\")" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "v1.Acelerar(30)\n", + "v2.Acelerar(60)\n", + "v3.Acelerar(90)\n", + "v1.Frenar(20)\n", + "v2.Doblar(-30)\n", + "v3.Doblar(-45)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "4) Agregar a la clase Vehiculo, un método que muestre su estado, es decir, a que velocidad se encuentra y su dirección. Y otro método que muestre color, tipo y cilindrada" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "class Vehiculo:\n", + " def __init__(self, color, tipo, cilindrada):\n", + " self.color = color\n", + " self.tipo = tipo\n", + " self.cilindrada = cilindrada\n", + " self.velocidad = 0\n", + " self.direccion = 0\n", + " \n", + " def Acelerar(self,vel):\n", + " self.velocidad += vel\n", + "\n", + " def Frenar(self,vel):\n", + " self.velocidad -= vel\n", + " \n", + " def Doblar(self, grados):\n", + " self.direccion += grados\n", + "\n", + " def Estado(self):\n", + " print('La velocidad del vehiculo es: ', self.velocidad, ' y la direccion', self.direccion)\n", + " \n", + " def Detalle(self):\n", + " print('soy', self.color, ', del tipo ',self.tipo,' y de cilindrada', self.cilindrada)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "La velocidad del vehiculo es: 0 y la direccion 0\n", + "soy verde , del tipo moto y de cilindrada 600\n" + ] + } + ], + "source": [ + "v1 = Vehiculo(\"verde\", \"moto\", \"600\")\n", + "v1.Estado()\n", + "v1.Detalle()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "5) Crear una clase que permita utilizar las funciones creadas en la práctica del módulo 6\n", + "Verificar Primo\n", + "Valor modal\n", + "Conversión grados\n", + "Factorial" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": {}, + "outputs": [], + "source": [ + "class Herramientas:\n", + " def __init__(self) -> None:\n", + " pass\n", + "\n", + " def Verificaprimo(self, num):\n", + " pri = True\n", + " for i in range(2,num):\n", + " if num%i == 0:\n", + " pri = False\n", + " break\n", + " return pri\n", + " \n", + " def Valormodal(self, lista, modo):\n", + " \n", + " contador = {} \n", + " for num in lista:\n", + " if num in contador.keys():\n", + " contador[num] += 1 \n", + " else:\n", + " contador[num] = 1\n", + " moda = []\n", + " maximo = 0\n", + " for numero, repeticion in contador.items():\n", + " if repeticion > maximo:\n", + " maximo = repeticion\n", + " moda = [numero]\n", + " elif repeticion == maximo:\n", + " moda.append(numero)\n", + " if modo == 'menor':\n", + " masRepetido_num = min(moda)\n", + " elif modo == 'mayor':\n", + " masRepetido_num = max(moda)\n", + " return masRepetido_num, maximo\n", + " \n", + " def Conversorgrados(self, valor, origen, destino):\n", + " if origen == 'celsius':\n", + " if destino == 'celsius':\n", + " valorDestino = valor\n", + " elif destino == 'farenheit':\n", + " valorDestino = (valor * 9/5) + 32\n", + " elif destino == 'kelvin':\n", + " valorDestino = valor + 273.15\n", + " else:\n", + " print(\"Parametro de destino no valido\")\n", + " elif origen == 'farenheit':\n", + " if destino == 'farenheit':\n", + " valorDestino = valor\n", + " elif destino == 'celsius':\n", + " valorDestino = ((valor - 32)*5) /9\n", + " elif destino == 'kelvin':\n", + " valorDestino = ((valor - 32)*5 /9) + 273.15\n", + " else:\n", + " print(\"Parametro de destino no valido\")\n", + " elif origen == 'kelvin':\n", + " if destino == 'kelvin':\n", + " valorDestino = valor\n", + " elif destino == 'farenheit':\n", + " valorDestino = (valor - 273.15) * (9/5) + 32\n", + " elif destino == 'celsius':\n", + " valorDestino = (valor - 273.15) \n", + " else:\n", + " print(\"Parametro de destino no valido\")\n", + " else:\n", + " print(\"parametro de origen no valido\")\n", + " return valorDestino\n", + " \n", + " def Factorial(self, numero):\n", + " if(type(numero) != int):\n", + " return 'El numero debe ser un entero'\n", + " if(numero < 0):\n", + " return 'El numero debe ser pisitivo'\n", + " if (numero > 1):\n", + " numero = numero * self.Factorial(numero - 1)\n", + " return numero" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "(5, 3)\n", + "274.15\n", + "120\n" + ] + } + ], + "source": [ + "h = Herramientas()\n", + "print(h.Verificaprimo(7))\n", + "modo = 'menor'\n", + "lis = [10,1,5,6,8,10,22,5,6,4,11,10,9,5]\n", + "print(h.Valormodal(lis,modo))\n", + "print(h.Conversorgrados(1,'celsius', 'kelvin'))\n", + "print(h.Factorial(5))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "7)Es necesario que la clase creada en el punto 5 contenga una lista, sobre la cual se apliquen las funciones incorporadas" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [], + "source": [ + "class Herramientas:\n", + " def __init__(self, lista_numeros):\n", + " self.lista = lista_numeros\n", + " \n", + " def Verificaprimo(self):\n", + " for i in self.lista:\n", + " if (self.__Verificaprimo(i)):\n", + " print('El elemento', i, 'SI es un numero primo')\n", + " else:\n", + " print('El elemento', i, 'NO es un numero primo')\n", + "\n", + " def Conversorgrados(self, origen, destino):\n", + " for i in self.lista:\n", + " print(i, 'grados', origen, 'son', self.__Conversorgrados(i, origen, destino),'grados',destino)\n", + " \n", + " def Factorial(self):\n", + " for i in self.lista:\n", + " print('El factorial de ', i, 'es', self.__Factorial(i))\n", + "\n", + " def __Verificaprimo(self, num):\n", + " pri = True\n", + " for i in range(2,num):\n", + " if num%i == 0:\n", + " pri = False\n", + " break\n", + " return pri\n", + " \n", + " def Valormodal(self, lista, modo='menor'):\n", + " \n", + " contador = {} \n", + " for num in self.lista:\n", + " if num in contador.keys():\n", + " contador[num] += 1 \n", + " else:\n", + " contador[num] = 1\n", + " moda = []\n", + " maximo = 0\n", + " for numero, repeticion in contador.items():\n", + " if repeticion > maximo:\n", + " maximo = repeticion\n", + " moda = [numero]\n", + " elif repeticion == maximo:\n", + " moda.append(numero)\n", + " if modo == 'menor':\n", + " masRepetido_num = min(moda)\n", + " elif modo == 'mayor':\n", + " masRepetido_num = max(moda)\n", + " return masRepetido_num, maximo\n", + " \n", + " def __Conversorgrados(self, valor, origen, destino):\n", + " if origen == 'celsius':\n", + " if destino == 'celsius':\n", + " valorDestino = valor\n", + " elif destino == 'farenheit':\n", + " valorDestino = (valor * 9/5) + 32\n", + " elif destino == 'kelvin':\n", + " valorDestino = valor + 273.15\n", + " else:\n", + " print(\"Parametro de destino no valido\")\n", + " elif origen == 'farenheit':\n", + " if destino == 'farenheit':\n", + " valorDestino = valor\n", + " elif destino == 'celsius':\n", + " valorDestino = ((valor - 32)*5) /9\n", + " elif destino == 'kelvin':\n", + " valorDestino = ((valor - 32)*5 /9) + 273.15\n", + " else:\n", + " print(\"Parametro de destino no valido\")\n", + " elif origen == 'kelvin':\n", + " if destino == 'kelvin':\n", + " valorDestino = valor\n", + " elif destino == 'farenheit':\n", + " valorDestino = (valor - 273.15) * (9/5) + 32\n", + " elif destino == 'celsius':\n", + " valorDestino = (valor - 273.15) \n", + " else:\n", + " print(\"Parametro de destino no valido\")\n", + " else:\n", + " print(\"parametro de origen no valido\")\n", + " return valorDestino\n", + " \n", + " def __Factorial(self, numero):\n", + " if(type(numero) != int):\n", + " return 'El numero debe ser un entero'\n", + " if(numero < 0):\n", + " return 'El numero debe ser pisitivo'\n", + " if (numero > 1):\n", + " numero = numero * self.__Factorial(numero - 1)\n", + " return numero" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "h = Herramientas([1,1,2,5,8,8,9,11,15,16,16,16,18,20])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "h.Conversorgrados('celsius','farenheit')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "h.Verificaprimo()" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "El valor modal es 16 y se reptie 3 veces\n" + ] + } + ], + "source": [ + "moda, repe = h.Valormodal(False)\n", + "print('El valor modal es', moda, 'y se reptie', repe, 'veces')" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "El factorial de 1 es 1\n", + "El factorial de 1 es 1\n", + "El factorial de 2 es 2\n", + "El factorial de 5 es 120\n", + "El factorial de 8 es 40320\n", + "El factorial de 8 es 40320\n", + "El factorial de 9 es 362880\n", + "El factorial de 11 es 39916800\n", + "El factorial de 15 es 1307674368000\n", + "El factorial de 16 es 20922789888000\n", + "El factorial de 16 es 20922789888000\n", + "El factorial de 16 es 20922789888000\n", + "El factorial de 18 es 6402373705728000\n", + "El factorial de 20 es 2432902008176640000\n" + ] + } + ], + "source": [ + "h.Factorial()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "8) Crear un archivo .py aparte y ubicar allí la clase generada en el punto anterior. Luego realizar la importación del módulo y probar alguna de sus funcione." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [], + "source": [ + "from Herramientas import *" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [], + "source": [ + "lis = Herramientas([10,1,5,6,8,10,22,5,6,4,11,10,9,5])\n" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "El elemento 10 NO es un numero primo\n", + "El elemento 1 SI es un numero primo\n", + "El elemento 5 SI es un numero primo\n", + "El elemento 6 NO es un numero primo\n", + "El elemento 8 NO es un numero primo\n", + "El elemento 10 NO es un numero primo\n", + "El elemento 22 NO es un numero primo\n", + "El elemento 5 SI es un numero primo\n", + "El elemento 6 NO es un numero primo\n", + "El elemento 4 NO es un numero primo\n", + "El elemento 11 SI es un numero primo\n", + "El elemento 10 NO es un numero primo\n", + "El elemento 9 NO es un numero primo\n", + "El elemento 5 SI es un numero primo\n" + ] + } + ], + "source": [ + "lis.Verificaprimo()" + ] + } + ], + "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.11.4" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/07 - Clases & OOP/__pycache__/Herramientas.cpython-311.pyc b/07 - Clases & OOP/__pycache__/Herramientas.cpython-311.pyc new file mode 100644 index 000000000..39f175079 Binary files /dev/null and b/07 - Clases & OOP/__pycache__/Herramientas.cpython-311.pyc differ diff --git a/07 - Clases & OOP/herramientas.py b/07 - Clases & OOP/herramientas.py index 3be4065b5..e4122df06 100644 --- a/07 - Clases & OOP/herramientas.py +++ b/07 - Clases & OOP/herramientas.py @@ -1,95 +1,89 @@ class Herramientas: def __init__(self, lista_numeros): self.lista = lista_numeros - - def verifica_primo(self): - ''' - Explico lo que hace la funcion - ''' + + def Verificaprimo(self): for i in self.lista: - if (self.__verifica_primo(i)): + if (self.__Verificaprimo(i)): print('El elemento', i, 'SI es un numero primo') else: print('El elemento', i, 'NO es un numero primo') - def conversion_grados(self, origen, destino): + def Conversorgrados(self, origen, destino): for i in self.lista: - print(i, 'grados', origen, 'son', self.__conversion_grados(i, origen, destino),'grados',destino) + print(i, 'grados', origen, 'son', self.__Conversorgrados(i, origen, destino),'grados',destino) - def factorial(self): + def Factorial(self): for i in self.lista: - print('El factorial de ', i, 'es', self.__factorial(i)) + print('El factorial de ', i, 'es', self.__Factorial(i)) - def __verifica_primo(self, nro): - es_primo = True - for i in range(2, nro): - if nro % i == 0: - es_primo = False + def __Verificaprimo(self, num): + pri = True + for i in range(2,num): + if num%i == 0: + pri = False break - return es_primo - - def valor_modal(self, menor): - lista_unicos = [] - lista_repeticiones = [] - if len(self.lista) == 0: - return None - if (menor): - self.lista.sort() - else: - self.lista.sort(reverse=True) - for elemento in self.lista: - if elemento in lista_unicos: - i = lista_unicos.index(elemento) - lista_repeticiones[i] += 1 + return pri + + def Valormodal(self, lista, modo='menor'): + + contador = {} + for num in self.lista: + if num in contador.keys(): + contador[num] += 1 else: - lista_unicos.append(elemento) - lista_repeticiones.append(1) - moda = lista_unicos[0] - maximo = lista_repeticiones[0] - for i, elemento in enumerate(lista_unicos): - if lista_repeticiones[i] > maximo: - moda = lista_unicos[i] - maximo = lista_repeticiones[i] - return moda, maximo - - def __conversion_grados(self, valor, origen, destino): - valor_destino = None - if (origen == 'celsius'): - if (destino == 'celsius'): - valor_destino = valor - elif (destino == 'farenheit'): - valor_destino = (valor * 9 / 5) + 32 - elif (destino == 'kelvin'): - valor_destino = valor + 273.15 + contador[num] = 1 + moda = [] + maximo = 0 + for numero, repeticion in contador.items(): + if repeticion > maximo: + maximo = repeticion + moda = [numero] + elif repeticion == maximo: + moda.append(numero) + if modo == 'menor': + masRepetido_num = min(moda) + elif modo == 'mayor': + masRepetido_num = max(moda) + return masRepetido_num, maximo + + def __Conversorgrados(self, valor, origen, destino): + if origen == 'celsius': + if destino == 'celsius': + valorDestino = valor + elif destino == 'farenheit': + valorDestino = (valor * 9/5) + 32 + elif destino == 'kelvin': + valorDestino = valor + 273.15 else: - print('Parámetro de Destino incorrecto') - elif (origen == 'farenheit'): - if (destino == 'celsius'): - valor_destino = (valor - 32) * 5 / 9 - elif (destino == 'farenheit'): - valor_destino = valor - elif (destino == 'kelvin'): - valor_destino = ((valor - 32) * 5 / 9) + 273.15 + print("Parametro de destino no valido") + elif origen == 'farenheit': + if destino == 'farenheit': + valorDestino = valor + elif destino == 'celsius': + valorDestino = ((valor - 32)*5) /9 + elif destino == 'kelvin': + valorDestino = ((valor - 32)*5 /9) + 273.15 else: - print('Parámetro de Destino incorrecto') - elif (origen == 'kelvin'): - if (destino == 'celsius'): - valor_destino = valor - 273.15 - elif (destino == 'farenheit'): - valor_destino = ((valor - 273.15) * 9 / 5) + 32 - elif (destino == 'kelvin'): - valor_destino = valor + print("Parametro de destino no valido") + elif origen == 'kelvin': + if destino == 'kelvin': + valorDestino = valor + elif destino == 'farenheit': + valorDestino = (valor - 273.15) * (9/5) + 32 + elif destino == 'celsius': + valorDestino = (valor - 273.15) else: - print('Parámetro de Destino incorrecto') + print("Parametro de destino no valido") else: - print('Parámetro de Origen incorrecto') - return valor_destino - - def __factorial(self, numero): + print("parametro de origen no valido") + return valorDestino + + def __Factorial(self, numero): if(type(numero) != int): return 'El numero debe ser un entero' if(numero < 0): return 'El numero debe ser pisitivo' if (numero > 1): - numero = numero * self.__factorial(numero - 1) + numero = numero * self.__Factorial(numero - 1) return numero \ No newline at end of file diff --git a/08 - Error Handling/__pycache__/checkpoint.cpython-311.pyc b/08 - Error Handling/__pycache__/checkpoint.cpython-311.pyc new file mode 100644 index 000000000..3e7634779 Binary files /dev/null and b/08 - Error Handling/__pycache__/checkpoint.cpython-311.pyc differ diff --git a/08 - Error Handling/__pycache__/herramientas.cpython-311.pyc b/08 - Error Handling/__pycache__/herramientas.cpython-311.pyc new file mode 100644 index 000000000..bbd28dc92 Binary files /dev/null and b/08 - Error Handling/__pycache__/herramientas.cpython-311.pyc differ diff --git a/08 - Error Handling/checkpoint.py b/08 - Error Handling/checkpoint.py index 71eb47fe4..59c75727a 100644 --- a/08 - Error Handling/checkpoint.py +++ b/08 - Error Handling/checkpoint.py @@ -12,7 +12,17 @@ def Factorial(numero): Factorial(-2) debe retornar nulo ''' #Tu código aca: - return 'Funcion incompleta' + if (type(numero) != int): + return None + if(numero < 1): + return None + factorial = 1 + while (numero > 1): + factorial = factorial * numero + numero -=1 + + + return factorial def EsPrimo(valor): ''' @@ -26,7 +36,14 @@ def EsPrimo(valor): EsPrimo(8) debe retornar False ''' #Tu código aca: - return 'Funcion incompleta' + + if (type(valor) != int): + return None + for i in range(2,int(valor/2)+1): + if valor%i == 0: + return False + + return True def ClaseAnimal(especie, color): ''' @@ -47,4 +64,15 @@ def ClaseAnimal(especie, color): a.CumpliAnios() -> debe devolver 3 ''' #Tu código aca: - return 'Funcion incompleta' + + class Animal: + def __init__(self, especie, color): + self.Especie = especie + self.Color = color + self.Edad = 0 + + def CumplirAnios(self): + self.Edad += 1 + return self.Edad + a = Animal(especie, color) + return a diff --git a/08 - Error Handling/herramientas.py b/08 - Error Handling/herramientas.py index 36947e769..96355dc02 100644 --- a/08 - Error Handling/herramientas.py +++ b/08 - Error Handling/herramientas.py @@ -1,8 +1,8 @@ class Herramientas: def __init__(self, lista_numeros): - if (type(lista_numeros) != list): - self.lista = [] - raise ValueError('Se ha creado una lista vacía. Se esperaba una lista de núemeros enteros') + if (type(lista_numeros) != list): #se le agregó + self.lista = [] # para el punto uno + raise ValueError('Se ha creado una lista vacía. Se esperaba una lista de núemeros enteros') # raise es paara levantar el error else: self.lista = lista_numeros @@ -16,16 +16,16 @@ def verifica_primo(self): return lista_primos def conversion_grados(self, origen, destino): - parametros_esperados = ['celsius','kelvin','farenheit'] - lista_conversion = [] - if str(origen) not in parametros_esperados: - print('Los parametros esperados son:', parametros_esperados) - return lista_conversion - if str(destino) not in parametros_esperados: - print('Los parametros esperados son:', parametros_esperados) - return lista_conversion + parametros_esperados = ['celsius','kelvin','farenheit'] # esto para + lista_conversion = [] # el punto numero + if str(origen) not in parametros_esperados: # tres + print('Los parametros de origen esperados son:', parametros_esperados) # + return lista_conversion #Retorno la lista vacía para que me guarde los valores + if str(destino) not in parametros_esperados: # + print('Los parametros de destino esperados son:', parametros_esperados) # + return lista_conversion # for i in self.lista: - lista_conversion.append(self.__conversion_grados(i, origen, destino)) + lista_conversion.append(self.__conversion_grados(i, origen, destino)) #guardar todos los valores return lista_conversion def factorial(self): diff --git a/08 - Error Handling/miTareaResuelta8.ipynb b/08 - Error Handling/miTareaResuelta8.ipynb new file mode 100644 index 000000000..ecebd1ea5 --- /dev/null +++ b/08 - Error Handling/miTareaResuelta8.ipynb @@ -0,0 +1,499 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1) Con la clase creada en el módulo 7, tener en cuenta diferentes casos en que el código pudiera arrojar error. Por ejemplo, en la creación del objeto recibimos una lista de números enteros pero ¿qué pasa si se envía otro tipo de dato?" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "import herramientas as h" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "ename": "ValueError", + "evalue": "Se ha creado una lista vacía. Se esperaba una lista de núemeros enteros", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[1;32mIn[21], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m h1 \u001b[39m=\u001b[39m h\u001b[39m.\u001b[39;49mHerramientas(\u001b[39m'\u001b[39;49m\u001b[39mHola\u001b[39;49m\u001b[39m'\u001b[39;49m)\n", + "File \u001b[1;32mc:\\Users\\agude\\Desktop\\Python-Prep\\08 - Error Handling\\herramientas.py:5\u001b[0m, in \u001b[0;36mHerramientas.__init__\u001b[1;34m(self, lista_numeros)\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[39mif\u001b[39;00m (\u001b[39mtype\u001b[39m(lista_numeros) \u001b[39m!=\u001b[39m \u001b[39mlist\u001b[39m):\n\u001b[0;32m 4\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mlista \u001b[39m=\u001b[39m []\n\u001b[1;32m----> 5\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\u001b[39m'\u001b[39m\u001b[39mSe ha creado una lista vacía. Se esperaba una lista de núemeros enteros\u001b[39m\u001b[39m'\u001b[39m) \n\u001b[0;32m 6\u001b[0m \u001b[39melse\u001b[39;00m:\n\u001b[0;32m 7\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mlista \u001b[39m=\u001b[39m lista_numeros\n", + "\u001b[1;31mValueError\u001b[0m: Se ha creado una lista vacía. Se esperaba una lista de núemeros enteros" + ] + } + ], + "source": [ + "h1 = h.Herramientas('Hola')" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [], + "source": [ + "h1 = h.Herramientas([2,3,5,6,2])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2) En la función que hace la conversión de grados, validar que los parámetros enviados sean los esperados, de no serlo, informar cuáles son los valores esperados." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import importlib #me recarga el módulo que estamos trayendo, para no reiniciar el kernel\n", + "importlib.reload(h)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Los parametros de destino esperados son: ['celsius', 'kelvin', 'farenheit']\n" + ] + }, + { + "data": { + "text/plain": [ + "[]" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import herramientas as h\n", + "h1 = h.Herramientas([2,3,5,6,2])\n", + "h1.conversion_grados(1,2)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[35.6, 37.4, 41.0, 42.8, 35.6]" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "h1.conversion_grados('celsius', 'farenheit')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "3) Importar el modulo \"unittest\" y crear los siguientes casos de pruebas sobre la clase utilizada en el punto 2
\n", + "Creacion del objeto incorrecta
\n", + "Creacion correcta del objeto
\n", + "Metodo valor_modal()
\n", + "\n", + "Se puede usar \"raise ValueError()\" en la creación de la clase para verificar el error. Investigar sobre esta funcionalidad." + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "import unittest" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [], + "source": [ + "class ProbandoMiClase(unittest.TestCase):\n", + " \n", + " def test_crear_objeto1(self):\n", + " param = 'hola'\n", + " self.assertRaises(ValueError, h.Herramientas, param)\n", + " #self.failUnlessRaises(ValueError, h.Herramientas, param)\n", + "\n", + " def test_crear_objeto2(self):\n", + " param = [1,2,2,5]\n", + " h1 = h.Herramientas(param)\n", + " self.assertEqual(h1.lista, param)\n", + "\n", + " def test_valor_modal(self):\n", + " lis = [1,2,1,3]\n", + " h1 = h.Herramientas(lis)\n", + " moda, veces = h1.valor_modal(False)\n", + " moda = [moda]\n", + " moda.append(veces)\n", + " resultado = [1, 2]\n", + " self.assertEqual(moda, resultado)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "test_crear_objeto1 (__main__.ProbandoMiClase.test_crear_objeto1) ... ok\n", + "test_crear_objeto2 (__main__.ProbandoMiClase.test_crear_objeto2) ... ok\n", + "test_valor_modal (__main__.ProbandoMiClase.test_valor_modal) ... ok\n", + "\n", + "----------------------------------------------------------------------\n", + "Ran 3 tests in 0.007s\n", + "\n", + "OK\n" + ] + }, + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "unittest.main(argv=[''], verbosity=2, exit=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "4) Probar una creación incorrecta y visualizar la salida del \"raise\"" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "ename": "ValueError", + "evalue": "Se ha creado una lista vacía. Se esperaba una lista de núemeros enteros", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[1;32mIn[35], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m h2 \u001b[39m=\u001b[39m h\u001b[39m.\u001b[39;49mHerramientas(\u001b[39m'\u001b[39;49m\u001b[39malgo\u001b[39;49m\u001b[39m'\u001b[39;49m)\n", + "File \u001b[1;32mc:\\Users\\agude\\Desktop\\Python-Prep\\08 - Error Handling\\herramientas.py:5\u001b[0m, in \u001b[0;36mHerramientas.__init__\u001b[1;34m(self, lista_numeros)\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[39mif\u001b[39;00m (\u001b[39mtype\u001b[39m(lista_numeros) \u001b[39m!=\u001b[39m \u001b[39mlist\u001b[39m): \u001b[39m#se le agregó\u001b[39;00m\n\u001b[0;32m 4\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mlista \u001b[39m=\u001b[39m [] \u001b[39m# para el punto uno\u001b[39;00m\n\u001b[1;32m----> 5\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\u001b[39m'\u001b[39m\u001b[39mSe ha creado una lista vacía. Se esperaba una lista de núemeros enteros\u001b[39m\u001b[39m'\u001b[39m) \u001b[39m# raise es paara levantar el error\u001b[39;00m\n\u001b[0;32m 6\u001b[0m \u001b[39melse\u001b[39;00m:\n\u001b[0;32m 7\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mlista \u001b[39m=\u001b[39m lista_numeros\n", + "\u001b[1;31mValueError\u001b[0m: Se ha creado una lista vacía. Se esperaba una lista de núemeros enteros" + ] + } + ], + "source": [ + "h2 = h.Herramientas('algo')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "6) Agregar casos de pruebas para el método verifica_primos() realizando el cambio en la clase, para que devuelva una lista de True o False en función de que el elemento en la posisicón sea o no primo" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [], + "source": [ + "class ProbandoMiClase2(unittest.TestCase):\n", + "\n", + " def test_verifica_primos1(self):\n", + " lis = [2,3,8,10,13]\n", + " h1 = h.Herramientas(lis)\n", + " primos = h1.verifica_primo()\n", + " primos_esperado = [True, True, False, False, True]\n", + " self.assertEqual(primos, primos_esperado)" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "importlib.reload(h)" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "test_crear_objeto1 (__main__.ProbandoMiClase.test_crear_objeto1) ... ok\n", + "test_crear_objeto2 (__main__.ProbandoMiClase.test_crear_objeto2) ... ok\n", + "test_valor_modal (__main__.ProbandoMiClase.test_valor_modal) ... ok\n", + "test_verifica_primos1 (__main__.ProbandoMiClase2.test_verifica_primos1) ... ok\n", + "\n", + "----------------------------------------------------------------------\n", + "Ran 4 tests in 0.005s\n", + "\n", + "OK\n" + ] + }, + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "unittest.main(argv=[''], verbosity=2, exit=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "7) Agregar casos de pruebas para el método conversion_grados()" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [], + "source": [ + "class ProbandoMiClase3(unittest.TestCase):\n", + "\n", + " def test_verifica_conversion1(self):\n", + " lis = [2,3,8,10,13]\n", + " h1 = h.Herramientas(lis)\n", + " grados = h1.conversion_grados('celsius','farenheit')\n", + " grados_esperado = [35.6, 37.4, 46.4, 50.0, 55.4]\n", + " self.assertEqual(grados, grados_esperado)" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "importlib.reload(h)" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "test_crear_objeto1 (__main__.ProbandoMiClase.test_crear_objeto1) ... ok\n", + "test_crear_objeto2 (__main__.ProbandoMiClase.test_crear_objeto2) ... ok\n", + "test_valor_modal (__main__.ProbandoMiClase.test_valor_modal) ... ok\n", + "test_verifica_primos1 (__main__.ProbandoMiClase2.test_verifica_primos1) ... ok\n", + "test_verifica_conversion1 (__main__.ProbandoMiClase3.test_verifica_conversion1) ... ok\n", + "\n", + "----------------------------------------------------------------------\n", + "Ran 5 tests in 0.008s\n", + "\n", + "OK\n" + ] + }, + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "unittest.main(argv=[''], verbosity=2, exit=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "8) Agregar casos de pruebas para el método factorial()" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [], + "source": [ + "class ProbandoMiClase4(unittest.TestCase):\n", + "\n", + " def test_verifica_factorial(self):\n", + " lis = [2,3,8,10,13]\n", + " h1 = h.Herramientas(lis)\n", + " factorial = h1.factorial()\n", + " factorial_esperado = [2, 6, 40320, 3628800, 6227020800]\n", + " self.assertEqual(factorial, factorial_esperado)" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "importlib.reload(h)" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "test_crear_objeto1 (__main__.ProbandoMiClase.test_crear_objeto1) ... ok\n", + "test_crear_objeto2 (__main__.ProbandoMiClase.test_crear_objeto2) ... ok\n", + "test_valor_modal (__main__.ProbandoMiClase.test_valor_modal) ... ok\n", + "test_verifica_primos1 (__main__.ProbandoMiClase2.test_verifica_primos1) ... ok\n", + "test_verifica_conversion1 (__main__.ProbandoMiClase3.test_verifica_conversion1) ... ok\n", + "test_verifica_factorial (__main__.ProbandoMiClase4.test_verifica_factorial) ... ok\n", + "\n", + "----------------------------------------------------------------------\n", + "Ran 6 tests in 0.009s\n", + "\n", + "OK\n" + ] + }, + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "unittest.main(argv=[''], verbosity=2, exit=False)" + ] + } + ], + "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.11.4" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +}