{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "RSmsnGzhmBvY" }, "source": [ "\n", " Tema 28: Introducción a la programación imperativa con Python\n", " \n", "\n", "----------\n", "\n", "[José A. Alonso](https://www.cs.us.es/~jalonso) \n", "[Departamento de Ciencias de la Computación e I.A.](https://www.cs.us.es) \n", "[Universidad de Sevilla](http://www.us.es) \n", "Sevilla, 23 de agosto de 2019" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> __Nota:__ La versión interactiva de este tema se encuentra en [Binder](https://mybinder.org/v2/gh/jaalonso/Temas_interactivos_de_PF_con_Haskell/master?urlpath=lab/tree/temas/Tema-28.ipynb)." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "yZzmN5vOmKss" }, "source": [ "# Python como calculadora" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "o6OXBaNOmcTr", "outputId": "a755c1dc-cf58-4cf9-d66c-64ee5f118802" }, "outputs": [ { "data": { "text/plain": [ "-87" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 * 5 + 6 - (100 + 3)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "HyU1MbRtm99J", "outputId": "2f8e28e2-4620-4d6f-c0d2-b8fcbc415ee9" }, "outputs": [ { "data": { "text/plain": [ "(4.0, 2.0)" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8/2, 8/4" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "HXzzxzNznIMc", "outputId": "fbf5cc01-a21b-43ca-dae7-779accb26e47" }, "outputs": [ { "data": { "text/plain": [ "(3, 1)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "7 // 2, 7 % 2" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "KcEoD2LmnbMg", "outputId": "81337587-7b81-443c-a353-fa214425e80b" }, "outputs": [ { "data": { "text/plain": [ "1024" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 ** 10" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "oF2Wt2WTnxib" }, "source": [ "# Variables y asignaciones" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "-MJksjlVn2K6", "outputId": "7606293c-84b7-43c1-8c0e-c6e76bf09a56" }, "outputs": [ { "data": { "text/plain": [ "16" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 8\n", "b = 2 * a\n", "b" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "iFyQGoouoNCN", "outputId": "437d51ef-ac7f-4f54-ae70-33bd849522e9" }, "outputs": [ { "data": { "text/plain": [ "24" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a + b" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "DIdQoHg1oRkV", "outputId": "867c7bb7-6627-4be8-e367-25cac5d1bf6c" }, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = a + 1\n", "a" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "Xf-V0d1l2De2", "outputId": "c50f19f1-9b9a-492f-c00c-c3b82d2b022e" }, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a, b = 2, 5\n", "a + 2 * b" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "M8C48pWG3Tew" }, "source": [ "# Definición de funciones" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "FYz2gPk03pS5" }, "source": [ "**Ejercicio 1**. Definir la función suma tal que suma(x, y) es la suma de x e y. . Por ejemplo,\n", "~~~\n", ">>> suma(2,3)\n", "5\n", "~~~" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "colab": {}, "colab_type": "code", "id": "p-FfLy5E3WD-" }, "outputs": [], "source": [ "def suma(x, y):\n", " return x+y" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "v_XY7tnF4IZ6", "outputId": "e598d23b-986c-438a-8584-d4bfa1e76718" }, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "suma(2, 3)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "3S6NvX494X0S" }, "source": [ "# Escritura y lectura" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "lAslXtd44jQq" }, "source": [ "**Ejercicio 2.** Definir el procedimiento suma que lea dos números y escriba su suma. Por ejemplo,\n", "~~~\n", ">>> suma()\n", "Escribe el primer número: 2\n", "Escribe el segundo número: 3\n", "La suma es: 5\n", "~~~" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "colab": {}, "colab_type": "code", "id": "OBcFWU1H4KNF" }, "outputs": [], "source": [ "def suma():\n", " a = eval(input(\"Escribe el primer número: \"))\n", " b = eval(input(\"Escribe el segundo número: \"))\n", " print(\"La suma es:\",a+b)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "colab_type": "code", "id": "mA36X4Ya5yH9", "outputId": "f6433ef0-f7de-4855-aa4f-1a01fff06c1b" }, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "Escribe el primer número: 2\n", "Escribe el segundo número: 3\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "La suma es: 5\n" ] } ], "source": [ "suma()" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "EqhJDkWJ6dLB" }, "source": [ "# La estructura condicional" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "0fJzBvcL6iLQ" }, "source": [ "## Condicionales simples" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "_fhrefIP6sR3" }, "source": [ "**Ejercicio 3.** Definir, usando condicionales, la función maximo tal que maximo(x,y) es el máximo de x e y. Por ejemplo,\n", "~~~\n", ">>> maximo(2, 5)\n", "5\n", ">>> maximo(2, 1)\n", "2\n", "~~~" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "colab": {}, "colab_type": "code", "id": "U7U-SRHU51xy" }, "outputs": [], "source": [ "def maximo(x, y) : \n", " if x > y:\n", " return x\n", " else:\n", " return y" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "k98NqxB67KW_", "outputId": "ae5a9f26-1d16-4b65-c713-1c5c91298124" }, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "maximo(2, 5)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "NJkaQfUF7Zto", "outputId": "a5aa7d57-7493-420b-8fdc-973d55f9ba23" }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "maximo (2, 1)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "MgnHSnGC7ihW" }, "source": [ "## Condicionales múltiples" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "jFbQzfn77n3D" }, "source": [ "**Ejercicio 4.** Definir la función signo tal que signo(x) es el signo de x. Por ejemplo,\n", "~~~\n", ">>> signo(5)\n", "1\n", ">>> signo(-7)\n", "- 1\n", ">>> signo(0)\n", "0\n", "~~~" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "colab": {}, "colab_type": "code", "id": "3K30z7RC7dl7" }, "outputs": [], "source": [ "def signo(x): \n", " if x > 0: \n", " return 1\n", " elif x < 0:\n", " return -1\n", " else:\n", " return 0" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "1Cc-K_9o8Rw2", "outputId": "0916d3e0-4a9b-4e8c-a49f-720a9c03c98c" }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "signo(5)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "r6Kd20Su8dtn", "outputId": "3b088728-e67d-4552-d519-84129756ff30" }, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "signo(-7)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "WlGJn1aP8ghu", "outputId": "72fd8e88-9df7-420e-a5c6-86383f707418" }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "signo(0)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "_L9lyY3F_fHV" }, "source": [ "# Estructuras iterativas" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Gdgq6_Ov_hw5" }, "source": [ "## Bucles mientras" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "cBb6i4zE_wj9" }, "source": [ "**Ejercicio 5.** Definir, con un bucle while, la función sumaImpares tal que sumaImpares(n) es la suma de los n primeros números impares. Por ejemplo,\n", "\n", "~~~\n", ">>> sumaImpares(3)\n", "9\n", ">>> sumaImpares(4)\n", "16\n", "~~~" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "colab": {}, "colab_type": "code", "id": "AhE7e3sm8iF0" }, "outputs": [], "source": [ "def sumaImpares(n):\n", " s, k = 0, 0 \n", " while k < n:\n", " s = s + 2*k + 1\n", " k = k + 1\n", " return s" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "rjBqgcSbAzLP", "outputId": "d1a1074a-fe43-4a23-9e8c-1ea214bd5986" }, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sumaImpares(3)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "wnErAFxkA2Xq", "outputId": "e7b70aca-9b64-4ab7-f297-3c298dde27e6" }, "outputs": [ { "data": { "text/plain": [ "16" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sumaImpares(4)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "bh21ciIUBGbO" }, "source": [ "**Ejercicio 6.** Definir la función mayorExponente tal que mayorExponente(a,n) es el mayor k tal que a^k divide a n. Por ejemplo,\n", "\n", "~~~\n", ">>> mayorExponente(2,40);\n", "3\n", "~~~" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "colab": {}, "colab_type": "code", "id": "0T4eNVETB0Sq" }, "outputs": [], "source": [ "def mayorExponente(a, n):\n", " k = 0\n", " while (n % a == 0):\n", " n = n/a\n", " k = k + 1\n", " return k" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "FnYolbVTA9JQ", "outputId": "23e269eb-a5cc-4d57-ea30-7e9956d6cad2" }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mayorExponente(2, 40)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "oubIiw8JCaXH" }, "source": [ "## Bucle para" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "JAruvRmOCmOx" }, "source": [ "**Ejercicio 7.** Definir, por iteración con for, la función fact tal que fact(n) es el factorial de n. Por ejemplo,\n", "\n", "~~~\n", ">>> fact 4\n", "24\n", "~~~" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "colab": {}, "colab_type": "code", "id": "Yhzp0yMwCWNa" }, "outputs": [], "source": [ "def fact(n): \n", " f = 1\n", " for k in range(1,n+1):\n", " f = f * k\n", " return f" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "QBzfVNW_DcsH", "outputId": "7c118d64-1fee-490e-ae58-7a321961a1be" }, "outputs": [ { "data": { "text/plain": [ "24" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fact(4)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "e9HDAKzBEcSL" }, "source": [ "## Bucle para sobre listas" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "_UVYfJjUEe2D" }, "source": [ "**Ejercicio 8.** Definir, por iteración, la función suma tal que suma(xs) es a suma de los números de la lista xs. Por ejemplo,\n", "~~~\n", ">>> suma([3,2,5])\n", "10\n", "~~~" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "colab": {}, "colab_type": "code", "id": "dFFgmQUZDeyw" }, "outputs": [], "source": [ "def suma(xs): \n", " r = 0\n", " for x in xs: \n", " r = x + r\n", " return r" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "R67fyFWeE7Pz", "outputId": "062609c6-fbc6-4898-c424-18ff4b31dc3c" }, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "suma([3, 2, 5])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Qkv2u9JlFEQM" }, "source": [ "# Recursión" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "7I3iZ-lqFJTY" }, "source": [ "**Ejercicio 9.** Definir, por recursión, la función fact tal que factR(n) es el factorial de n. Por ejemplo,\n", "~~~\n", ">>> fact 4\n", "24\n", "~~~" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "colab": {}, "colab_type": "code", "id": "cSt25__2E-rZ" }, "outputs": [], "source": [ "def fact(n):\n", " if n == 0: \n", " return 1\n", " else: \n", " return n * fact(n-1)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "1qHs5AK-Fglc", "outputId": "d5c2e29d-cc7b-45f9-86cd-87b704137216" }, "outputs": [ { "data": { "text/plain": [ "24" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fact(4)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "-yDKWVM6CkKL" }, "source": [ "# La función de Takeuchi" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "colab": {}, "colab_type": "code", "id": "4RuLm35FCqOY" }, "outputs": [], "source": [ "def tak(x,y,z):\n", " if x <= y:\n", " return y\n", " else:\n", " return tak(tak(x - 1, y, z),\n", " tak(y - 1, z, x),\n", " tak(z - 1, x, y))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "8eI1r8WLC4gP" }, "source": [ "Importación de la librería para medir el tiempo." ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "colab": {}, "colab_type": "code", "id": "Z79gNnvCDBkT" }, "outputs": [], "source": [ "import time" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "lu50gVv7DMKm" }, "source": [ "Primer experimento" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "RCnw-plfDJzh", "outputId": "be59fa00-5d4c-4c85-e02f-d8879d61b3ae" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Tiempo = 0.33638763427734375 segundos \n" ] } ], "source": [ "tiempo_inicial = time.time()\n", "tak(12,6,1)\n", "print(\"Tiempo = %s segundos \" % (time.time() - tiempo_inicial)) " ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "VeOh0Q5vDZlC" }, "source": [ "Segundo experimento" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "7HjadObiKz8y", "outputId": "553e4da1-6aac-452c-942d-c99ef0b1ad20" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Tiempo = 1.9111294746398926 segundos \n" ] } ], "source": [ "tiempo_inicial = time.time()\n", "tak(13,6,1)\n", "print(\"Tiempo = %s segundos \" % (time.time() - tiempo_inicial)) " ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "4nBGOZGrKuuz" }, "source": [ "Tercer experimento" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "bfGmN8tALA80", "outputId": "7be781e9-a6bb-4e08-fd87-011b47512286" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Tiempo = 11.704586267471313 segundos \n" ] } ], "source": [ "tiempo_inicial = time.time()\n", "tak(14,6,1)\n", "print(\"Tiempo = %s segundos \" % (time.time() - tiempo_inicial)) " ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "qOM_o6esK8TV" }, "source": [ "Cuarto experimento" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "V8jzWZM8DdtG", "outputId": "4019760b-378b-49dd-c03b-b8d75a391dd6" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Tiempo = 540.393595457077 segundos \n" ] } ], "source": [ "tiempo_inicial = time.time()\n", "tak(16,6,1)\n", "print(\"Tiempo = %s segundos \" % (time.time() - tiempo_inicial)) " ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "Programacion_imperativa_en_Python.ipynb", "provenance": [], "version": "0.3.2" }, "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.3" }, "toc-autonumbering": true }, "nbformat": 4, "nbformat_minor": 4 }