Commit 210cff18 authored by Aldo Eduardo Niebla Cruz's avatar Aldo Eduardo Niebla Cruz

Merge branch 'aniebla' of gitlab.geoint.mx:mario.chirinos/tap1012 into aniebla

parents c9714b94 2f3fac54
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 4 Examen Unidad 1\n",
"Escribe una función o classe y su docstring para los siguientes ejercicios. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.1 Obten el promedio de los numeros en una lista."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Trying:\n",
" a = [2,7,43,87,3,65]\n",
"Expecting nothing\n",
"ok\n",
"Trying:\n",
" promedio(a)\n",
"Expecting:\n",
" 34.5\n",
"ok\n",
"1 items had no tests:\n",
" __main__\n",
"1 items passed all tests:\n",
" 2 tests in __main__.promedio\n",
"2 tests in 2 items.\n",
"2 passed and 0 failed.\n",
"Test passed.\n"
]
},
{
"data": {
"text/plain": [
"TestResults(failed=0, attempted=2)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def promedio(lista):\n",
" '''La función obtiene el promedio de los numeros en una lista.\n",
" \n",
" Args:\n",
" lista(list): Lista que contenga los valores a evaluar\n",
" \n",
" Ejemplo:\n",
" >>> a = [2,7,43,87,3,65]\n",
" >>> promedio(a)\n",
" 34.5\n",
" '''\n",
" return sum(lista) / len(lista)\n",
"\n",
"a = [2,7,43,87,3,65]\n",
"promedio(a)\n",
"\n",
"import doctest\n",
"doctest.testmod(verbose=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.2 Regresa todos los numeros enteros en una lista dividida por un numero."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Trying:\n",
" b = [10, 20, 30, 40, 50]\n",
"Expecting nothing\n",
"ok\n",
"Trying:\n",
" num = 4\n",
"Expecting nothing\n",
"ok\n",
"Trying:\n",
" divide(b,num)\n",
"Expecting:\n",
" [5.0, 10.0]\n",
"ok\n",
"1 items had no tests:\n",
" __main__\n",
"1 items passed all tests:\n",
" 3 tests in __main__.divide\n",
"3 tests in 2 items.\n",
"3 passed and 0 failed.\n",
"Test passed.\n"
]
},
{
"data": {
"text/plain": [
"TestResults(failed=0, attempted=3)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def divide(lista, numero):\n",
" '''La función Regresa todos los numeros enteros en una lista dividida por un numero\n",
" \n",
" Args:\n",
" lista(list): Lista que contenga los valores a evaluar\n",
" numero(int): Numero que será dividido entre cada elemento de la lista\n",
" \n",
" Ejemplo:\n",
" >>> b = [10, 20, 30, 40, 50]\n",
" >>> num = 4\n",
" >>> divide(b,num)\n",
" [5.0, 10.0]\n",
" '''\n",
" return list( map(lambda z: z/numero, filter(lambda x: x%numero == 0, lista)) )\n",
"\n",
"b = [10, 20, 30, 40, 50]\n",
"num = 4 \n",
"divide(b,num)\n",
"\n",
"import doctest\n",
"doctest.testmod(verbose=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.3 Encuentra el factorial de un numero usando recursion.\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Trying:\n",
" num = 5\n",
"Expecting nothing\n",
"ok\n",
"Trying:\n",
" factorial(num)\n",
"Expecting:\n",
" 120\n",
"ok\n",
"1 items had no tests:\n",
" __main__\n",
"1 items passed all tests:\n",
" 2 tests in __main__.factorial\n",
"2 tests in 2 items.\n",
"2 passed and 0 failed.\n",
"Test passed.\n"
]
},
{
"data": {
"text/plain": [
"TestResults(failed=0, attempted=2)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def factorial(n):\n",
" '''La función Encuentra el factorial de un numero usando recursion\n",
" \n",
" Args:\n",
" n(int): El numero al que se quiere calcular su factorial\n",
" \n",
" Ejemplo:\n",
" >>> num = 5\n",
" >>> factorial(num)\n",
" 120\n",
" '''\n",
" return n if n == 1 else n*factorial(n-1)\n",
"\n",
"num = 6 \n",
"factorial(num)\n",
"\n",
"import doctest\n",
"doctest.testmod(verbose=True)"
]
},
{
"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": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Trying:\n",
" minimo = 10\n",
"Expecting nothing\n",
"ok\n",
"Trying:\n",
" maximo = 300\n",
"Expecting nothing\n",
"ok\n",
"Trying:\n",
" palindromo_impar(minimo,maximo)\n",
"Expecting:\n",
" [11, 33, 55, 77, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]\n",
"ok\n",
"1 items had no tests:\n",
" __main__\n",
"1 items passed all tests:\n",
" 3 tests in __main__.palindromo_impar\n",
"3 tests in 2 items.\n",
"3 passed and 0 failed.\n",
"Test passed.\n"
]
},
{
"data": {
"text/plain": [
"TestResults(failed=0, attempted=3)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def palindromo_impar(minimo, maximo):\n",
" '''La función Encuentra todos los numeros que sean impares y palindromos en un rango dado.\n",
" \n",
" Args:\n",
" minimo(int): El valor inicial del rango a evaluar\n",
" maximo(int): El valor fial del rango a evaluar\n",
" \n",
" Ejemplo:\n",
" >>> minimo = 10\n",
" >>> maximo = 300\n",
" >>> palindromo_impar(minimo,maximo)\n",
" [11, 33, 55, 77, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]\n",
" '''\n",
" \n",
" palindromo = filter(lambda k: list(str(k)) == list(reversed(str(k))), range(minimo,maximo))\n",
" \n",
" return [i for i in palindromo if i %2 != 0]\n",
"\n",
"minimo = 10\n",
"maximo = 400\n",
"palindromo_impar(minimo,maximo)\n",
"\n",
"import doctest\n",
"doctest.testmod(verbose=True)"
]
},
{
"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": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introduce una palabra:manopla\n",
"Introduce numero de intentos:3\n",
"_ _ _ _ _ _ _\n",
"\n",
"Dame una letra: o\n",
"\n",
"_ _ _ o _ _ _\n",
"\n",
"Dame una letra: a\n",
"\n",
"_ a _ o _ _ a\n",
"\n",
"Dame una letra: n\n",
"\n",
"_ a n o _ _ a\n",
"\n",
"Dame una letra: p\n",
"\n",
"_ a n o p _ a\n",
"\n",
"Dame una letra: q\n",
"\n",
"Error!!, te quedan 2 intentos\n",
"\n",
"_ a n o p _ a\n",
"\n",
"Dame una letra: m\n",
"\n",
"m a n o p _ a\n",
"\n",
"Dame una letra: l\n",
"\n",
"Ganaste!!, la palabra es \" manopla \"\n",
"Trying:\n",
" ahorcado(palabra, intentos)\n",
"Expecting:\n",
" Introduce una palabra:manopla\n",
" Introduce numero de intentos:3\n",
" _ _ _ _ _ _ _\n",
"**********************************************************************\n",
"File \"__main__\", line 9, in __main__.ahorcado\n",
"Failed example:\n",
" ahorcado(palabra, intentos)\n",
"Exception raised:\n",
" Traceback (most recent call last):\n",
" File \"/usr/lib/python3.5/doctest.py\", line 1321, in __run\n",
" compileflags, 1), test.globs)\n",
" File \"<doctest __main__.ahorcado[0]>\", line 1, in <module>\n",
" ahorcado(palabra, intentos)\n",
" NameError: name 'intentos' is not defined\n",
"1 items had no tests:\n",
" __main__\n",
"**********************************************************************\n",
"1 items had failures:\n",
" 1 of 1 in __main__.ahorcado\n",
"1 tests in 2 items.\n",
"0 passed and 1 failed.\n",
"***Test Failed*** 1 failures.\n"
]
},
{
"data": {
"text/plain": [
"TestResults(failed=1, attempted=1)"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def ahorcado(palabra, intentos):\n",
" '''La función recibe una palabra y un numero e interactua con el usuario para jugar *ahorcado*.\n",
" \n",
" Args:\n",
" palabra(str): La palabra a adivinar\n",
" intentos(int): el valor del numero maximo de intentos para adivinar la palabra\n",
" \n",
" Ejemplo:\n",
" >>> ahorcado(palabra, intentos)\n",
" Introduce una palabra:manopla\n",
" Introduce numero de intentos:3\n",
" _ _ _ _ _ _ _\n",
" '''\n",
"\n",
" PalabraAdiv = list(palabra)\n",
" PalabraMost = ['_' for item in PalabraAdiv] \n",
"\n",
" while intentos > 0:\n",
"\n",
" print(' '.join(PalabraMost)) # Imprime los guiones\n",
"\n",
" letra = input('\\nDame una letra: ')\n",
" print()\n",
"\n",
" if letra not in PalabraAdiv: #Intento Fallido\n",
" intentos -= 1\n",
" print('Error!!, te quedan', intentos, 'intentos\\n')\n",
" else:\n",
" for key, value in enumerate(PalabraAdiv): #Acertó en la letra\n",
" if value == letra:\n",
" PalabraMost[key] = value\n",
"\n",
" if intentos == 0:\n",
" print('Perdiste!!, la palabra es \"',''.join(PalabraAdiv),'\"')\n",
" break\n",
" if PalabraAdiv == PalabraMost: \n",
" print('Ganaste!!, la palabra es \"',''.join(PalabraAdiv),'\"')\n",
" break\n",
" \n",
"palabra = input('Introduce una palabra:')\n",
"numero = int( input('Introduce numero de intentos:') )\n",
"ahorcado(palabra, numero)\n",
"\n",
"import doctest\n",
"doctest.testmod(verbose=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"## 4.6 Escribe una funcion que reciva un texto y regrese un diccionario ordenado con el numero de occurencias de cada palabra en el texto."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Trying:\n",
" frase = 'zayra prueba el ejercicio prueba un perfume prueba el pastel'\n",
"Expecting nothing\n",
"ok\n",
"Trying:\n",
" cuenta_palabras(frase)\n",
"Expecting:\n",
" [('ejercicio', 1), ('el', 2), ('pastel', 1), ('perfume', 1), ('prueba', 3), ('un', 1), ('zayra', 1)]\n",
"ok\n",
"1 items had no tests:\n",
" __main__\n",
"1 items passed all tests:\n",
" 2 tests in __main__.cuenta_palabras\n",
"2 tests in 2 items.\n",
"2 passed and 0 failed.\n",
"Test passed.\n"
]
},
{
"data": {
"text/plain": [
"TestResults(failed=0, attempted=2)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def cuenta_palabras(texto):\n",
" '''La función recibe un texto y regrese un diccionario ordenado con el numero de occurencias de cada palabra en el texto\n",
" \n",
" Args:\n",
" texto(str): La cadena de texto a evaluar\n",
" \n",
" Ejemplo:\n",
" >>> frase = 'zayra prueba el ejercicio prueba un perfume prueba el pastel'\n",
" >>> cuenta_palabras(frase)\n",
" [('ejercicio', 1), ('el', 2), ('pastel', 1), ('perfume', 1), ('prueba', 3), ('un', 1), ('zayra', 1)]\n",
" '''\n",
" cuenta = {}\n",
" \n",
" for palabra in texto.split():\n",
" if palabra in cuenta:\n",
" cuenta[palabra] += 1\n",
" else:\n",
" cuenta[palabra] = 1\n",
" \n",
" return sorted(cuenta.items(), key=lambda x: x[0])\n",
"\n",
"frase = 'zayra prueba el ejercicio prueba un perfume prueba el pastel'\n",
"cuenta_palabras(frase)\n",
"\n",
"import doctest\n",
"doctest.testmod(verbose=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.7 Escribe una clase que convierta un numero entero a numero romano."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"MMXIX\n",
"Trying:\n",
" print(entero_romano().convierte(2019))\n",
"Expecting:\n",
" MMXIX\n",
"ok\n",
"2 items had no tests:\n",
" __main__\n",
" __main__.entero_romano\n",
"1 items passed all tests:\n",
" 1 tests in __main__.entero_romano.convierte\n",
"1 tests in 3 items.\n",
"1 passed and 0 failed.\n",
"Test passed.\n"
]
},
{
"data": {
"text/plain": [
"TestResults(failed=0, attempted=1)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class entero_romano:\n",
" def convierte(self, numero):\n",
" '''El metodo \"convierte\" de la clase \"entero_romano\" convierte un numero entero a numero romano.\n",
" \n",
" Args:\n",
" self(str): Variable intrinseca de instancia\n",
" numero(int): Numero entero que se desea convertir a numero romano\n",
" \n",
" Ejemplo: \n",
" >>> print(entero_romano().convierte(2019))\n",
" MMXIX\n",
" '''\n",
" enteros = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\n",
" romanos = [\"M\", \"CM\", \"D\", \"CD\", \"C\", \"XC\", \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\"]\n",
" romano_convertido = ''\n",
" i = 0\n",
" while numero > 0:\n",
" for _ in range(numero // enteros[i]):\n",
" romano_convertido += romanos[i]\n",
" numero -= enteros[i]\n",
" i += 1\n",
" return romano_convertido\n",
"\n",
"#Cabe mencionar que para numeros mayores a 3999 el programa no sigue las reglas originales, \n",
"#ya que no encontre forma de poner un simbolo arriba al número romano\n",
"print(entero_romano().convierte(2019))\n",
"\n",
"import doctest\n",
"doctest.testmod(verbose=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4.8 Escribe una funcion que regrese el cuadrado mágico del tamaño indicado.\n",
"[Wikipedia](https://es.wikipedia.org/wiki/Cuadrado_m%C3%A1gico) Cuadrado Mágico"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"def ejercicio8(n):\n",
" pass\n",
"#complidado de programar :/"
]
},
{
"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.5.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
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