diff --git a/lab-python-functions.ipynb b/lab-python-functions.ipynb index 7e1dcbd..3d9a1b0 100644 --- a/lab-python-functions.ipynb +++ b/lab-python-functions.ipynb @@ -13,7 +13,7 @@ "id": "6f8e446f-16b4-4e21-92e7-9d3d1eb551b6", "metadata": {}, "source": [ - "Objective: Practice how to define and call functions, pass arguments, return values, and handle scope. " + "Objetivo: practicar cómo definir y llamar funciones, pasar argumentos, devolver valores y manejar el alcance." ] }, { @@ -28,22 +28,42 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "id": "df908bed-acc6-4b67-b33a-f3b1c564a49f", "metadata": {}, "outputs": [], "source": [ + "lst = [1,2,3,3,3,3,4,5]\n", "def get_unique_list(lst):\n", " \"\"\"\n", - " Takes a list as an argument and returns a new list with unique elements from the first list.\n", + " Toma una lista como argumento y devuelve una nueva lista con elementos únicos de la primera lista.\n", "\n", - " Parameters:\n", - " lst (list): The input list.\n", + " Parámetros:\n", + " lst (lista): la lista de entrada.\n", "\n", - " Returns:\n", - " list: A new list with unique elements from the input list.\n", + " Devoluciones:\n", + " lista: una nueva lista con elementos únicos de la lista de entrada.\n", " \"\"\"\n", - " # your code goes here\n" + " return list(set(lst))" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "813c1240", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5]\n" + ] + } + ], + "source": [ + "new_list = get_unique_list(lst)\n", + "print(new_list)" ] }, { @@ -60,22 +80,41 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "id": "7d5c8e34-a116-4428-ab9d-e0e15e338fff", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(2, 8)\n" + ] + } + ], "source": [ + "string = \"Hello World\"\n", "def count_case(string):\n", " \"\"\"\n", " Returns the number of uppercase and lowercase letters in the given string.\n", "\n", " Parameters:\n", - " string (str): The string to count uppercase and lowercase letters in.\n", + " string (string): The string for counting uppercase and lowercase letters.\n", "\n", " Returns:\n", " A tuple containing the count of uppercase and lowercase letters in the string.\n", " \"\"\"\n", - " # your code goes here" + " uppercase = 0\n", + " lowercase = 0\n", + "\n", + " for word in string:\n", + " if word.isupper():\n", + " uppercase += 1\n", + " elif word.islower():\n", + " lowercase += 1\n", + " return uppercase, lowercase\n", + "\n", + "print(count_case(string))" ] }, { @@ -92,13 +131,32 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "c15b91d4-cfd6-423b-9f36-76012b8792b8", + "execution_count": 18, + "id": "4eac951a", "metadata": {}, "outputs": [], "source": [ - "import string\n", + "import string" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "c15b91d4-cfd6-423b-9f36-76012b8792b8", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Note this is an example Good day \n", + "7\n" + ] + } + ], + "source": [ "\n", + "sentence = \"Note : this is an example !!! Good day : )\"\n", "def remove_punctuation(sentence):\n", " \"\"\"\n", " Removes all punctuation marks (commas, periods, exclamation marks, question marks) from a sentence.\n", @@ -109,20 +167,27 @@ " Returns:\n", " str: The sentence without any punctuation marks.\n", " \"\"\"\n", - " # your code goes here\n", + " sentence_limpia = sentence.translate(str.maketrans('','', string.punctuation))\n", + " return sentence_limpia\n", + "\n", + "print(remove_punctuation(sentence))\n", "\n", "def word_count(sentence):\n", " \"\"\"\n", - " Counts the number of words in a given sentence. To do this properly, first it removes punctuation from the sentence.\n", - " Note: A word is defined as a sequence of characters separated by spaces. We can assume that there will be no leading or trailing spaces in the input sentence.\n", + " Cuenta el número de palabras en una oración determinada. Para hacer esto correctamente, primero elimina la puntuación de la oración.\n", + " Nota: Una palabra se define como una secuencia de caracteres separados por espacios. Podemos suponer que no habrá espacios iniciales ni finales en la oración de entrada.\n", " \n", - " Parameters:\n", - " sentence (str): A string representing a sentence.\n", + " Parámetros:\n", + " oración (cadena): una cadena que representa una oración.\n", "\n", - " Returns:\n", - " int: The number of words in the sentence.\n", + " Devoluciones:\n", + " int: el número de palabras de la oración.\n", " \"\"\"\n", - " # your code goes here" + " sentence_limpia = sentence.translate(str.maketrans('','', string.punctuation))\n", + " sentence2 = len(sentence_limpia.split())\n", + " return sentence2\n", + "\n", + "print(word_count(sentence))" ] }, { @@ -139,41 +204,90 @@ ] }, { - "cell_type": "code", - "execution_count": null, - "id": "f7cfd32a-f559-47ff-81c1-2576bd4fe3bf", + "cell_type": "markdown", + "id": "fb01ccba-2ecc-4eea-b9a9-2bf9d29e8804", "metadata": {}, - "outputs": [], "source": [ - "# your code goes here" + "## Challenge 2: Build a Calculator\n", + "\n", + "En este ejercicio, creará una calculadora utilizando funciones de Python. La calculadora podrá realizar operaciones aritméticas básicas como suma, resta, multiplicación y división.\n", + "\n", + "Instrucciones\n", + "- Definir cuatro funciones para suma, resta, multiplicación y división.\n", + "- Cada función debe tomar dos argumentos, realizar la operación aritmética respectiva y devolver el resultado.\n", + "- Definir otra función llamada \"calcular\" que tome tres argumentos: dos operandos y un operador.\n", + "- La función \"calcular\" debe utilizar una declaración condicional para determinar qué función aritmética llamar en función del argumento del operador.\n", + "- La función \"calcular\" debería llamar a la función aritmética apropiada y devolver el resultado.\n", + "- Pruebe su función \"calcular\" llamándola con diferentes parámetros de entrada.\n" ] }, { - "cell_type": "markdown", - "id": "fb01ccba-2ecc-4eea-b9a9-2bf9d29e8804", + "cell_type": "code", + "execution_count": 34, + "id": "57f9afc7-8626-443c-9c3e-eb78ef503193", "metadata": {}, + "outputs": [], "source": [ - "## Challenge 2: Build a Calculator\n", + "def sumar(a,b):\n", + " sum = a+b\n", + " return sum\n", "\n", - "In this exercise, you will build a calculator using Python functions. The calculator will be able to perform basic arithmetic operations like addition, subtraction, multiplication, and division.\n", + "def restar(a,b):\n", + " resta = a-b\n", + " return resta\n", "\n", - "Instructions\n", - "- Define four functions for addition, subtraction, multiplication, and division.\n", - "- Each function should take two arguments, perform the respective arithmetic operation, and return the result.\n", - "- Define another function called \"calculate\" that takes three arguments: two operands and an operator.\n", - "- The \"calculate\" function should use a conditional statement to determine which arithmetic function to call based on the operator argument.\n", - "- The \"calculate\" function should then call the appropriate arithmetic function and return the result.\n", - "- Test your \"calculate\" function by calling it with different input parameters.\n" + "def multiplicar(a, b):\n", + " multiplicacion = a*b\n", + " return multiplicacion\n", + "\n", + "def dividir(a, b):\n", + " division = a/b\n", + " return division" ] }, { "cell_type": "code", - "execution_count": null, - "id": "57f9afc7-8626-443c-9c3e-eb78ef503193", + "execution_count": 35, + "id": "7be97e2e", "metadata": {}, "outputs": [], "source": [ - "# your code goes here" + "def calcular(num1, num2, operador):\n", + " if operador == sumar:\n", + " return sumar(num1, num2)\n", + " \n", + " elif operador == restar:\n", + " return restar(num1, num2)\n", + " \n", + " elif operador == multiplicar:\n", + " return multiplicar(num1, num2)\n", + " \n", + " elif operador == dividir:\n", + " return dividir(num1, num2)\n", + " else:\n", + " print(\"error: operador no valido\")" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "2ac3b3fc", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.5\n", + "16.9\n", + "120\n" + ] + } + ], + "source": [ + "print(calcular(3,6, dividir))\n", + "print(calcular(10, 6.9, sumar))\n", + "print(calcular(8,15, multiplicar))" ] }, { @@ -183,21 +297,88 @@ "source": [ "### Bonus: args and kwargs\n", "\n", - "Update the previous exercise so it allows for adding, subtracting, and multiplying more than 2 numbers.\n", + "Actualice el ejercicio anterior para que permita sumar, restar y multiplicar más de 2 números.\n", "\n", - "The calculator will be able to perform basic arithmetic operations like addition, subtraction, multiplication, and division on multiple numbers.\n", + "La calculadora podrá realizar operaciones aritméticas básicas como suma, resta, multiplicación y división de varios números.\n", "\n", "*Hint: use args or kwargs. Recommended external resource: [Args and Kwargs in Python](https://www.geeksforgeeks.org/args-kwargs-python/)*" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 40, "id": "ff3e816c-13ab-447d-a6f2-bb47a8fad2e2", "metadata": {}, "outputs": [], "source": [ - "# your code goes here" + "def sumar(*args):\n", + " result = 0\n", + " for num in args:\n", + " result += num\n", + " return result\n", + "\n", + "def restar(*args):\n", + " result = 0\n", + " for num in args:\n", + " result -= num\n", + " return result\n", + "\n", + "def multiplicar(*args):\n", + " result = 1\n", + " for num in args:\n", + " result *= num\n", + " return result\n", + "\n", + "def dividir(*args):\n", + " result = args[0]\n", + " for num in args[1:]:\n", + " result /= num\n", + " return result" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "id": "7e4a34bd", + "metadata": {}, + "outputs": [], + "source": [ + "def calcular(operador, *args):\n", + " if operador == sumar:\n", + " return sumar(*args)\n", + " \n", + " elif operador == restar:\n", + " return restar(*args)\n", + " \n", + " elif operador == multiplicar:\n", + " return multiplicar(*args)\n", + " \n", + " elif operador == dividir:\n", + " return dividir(*args)\n", + " else:\n", + " print(\"error: operador no valido\")" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "id": "4e86e55a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.05555555555555555\n", + "26.9\n", + "240\n" + ] + } + ], + "source": [ + "print(calcular(dividir, 3, 6, 9))\n", + "print(calcular(sumar, 10, 6.9, 10))\n", + "print(calcular(multiplicar, 8, 15, 2))" ] }, { @@ -213,41 +394,40 @@ "id": "56780ce8-6610-4fb5-a4ef-22cd46af83d2", "metadata": {}, "source": [ - "Moving the functions created in Challenge 1 to a Python file.\n", + "Mover las funciones creadas en el Desafío 1 a un archivo Python.\n", "\n", - "- In the same directory as your Jupyter Notebook, create a new Python file called `functions.py`.\n", - "- Copy and paste the functions you created earlier in the Jupyter Notebook into the functions.py file. Rename the functions to `get_unique_list_f, count_case_f, remove_punctuation_f, word_count_f`. Add the _f suffix to each function name to ensure that you're calling the functions from your file.\n", - "- Save the `functions.py` file and switch back to the Jupyter Notebook.\n", - "- In a new cell, import the functions from functions.py\n", - "- Call each function with some sample input to test that they're working properly.\n", + "- En el mismo directorio que su Jupyter Notebook, cree un nuevo archivo Python llamado `functions.py`.\n", + "- Copie y pegue las funciones que creó anteriormente en Jupyter Notebook en el archivo funciones.py. Cambie el nombre de las funciones a `get_unique_list_f, count_case_f, remove_punctuation_f, word_count_f`. Agregue el sufijo _f a cada nombre de función para asegurarse de que está llamando a las funciones desde su archivo.\n", + "- Guarde el archivo `functions.py` y vuelva a Jupyter Notebook.\n", + "- En una nueva celda, importe las funciones desde funciones.py\n", + "- Llame a cada función con alguna entrada de muestra para probar que funcionan correctamente.\n", "\n", - "There are several ways to import functions from a Python module such as functions.py to a Jupyter Notebook:\n", + "Hay varias formas de importar funciones desde un módulo de Python, como funciones.py, a un Jupyter Notebook:\n", "\n", - "1. Importing specific functions: If you only need to use a few functions from the module, you can import them individually using the from keyword. This way, you can call the functions directly using their names, without having to use the module name. For example:\n", + "1. Importar funciones específicas: si solo necesita usar algunas funciones del módulo, puede importarlas individualmente usando la palabra clave from. De esta manera, puedes llamar a las funciones directamente usando sus nombres, sin tener que usar el nombre del módulo. Por ejemplo:\n", "\n", - "```python\n", - "from function_file import function_name\n", + "```pitón\n", + "desde archivo_función importar nombre_función\n", "\n", - "function_name(arguments)```\n", + "nombre_función(argumentos)```\n", "\n", - "2. Importing the entire module: You can import the entire module using the import keyword followed by the name of the module. Then, you can call the functions using the module_name.function_name() syntax. Example:\n", + "2. Importar el módulo completo: puede importar el módulo completo usando la palabra clave import seguida del nombre del módulo. Luego, puede llamar a las funciones usando la sintaxis module_name.function_name(). Ejemplo:\n", "\n", - "```python\n", - "import function_file\n", + "```pitón\n", + "importar archivo_función\n", "\n", - "function_file.function_name()\n", + "archivo_función.nombre_función()\n", "```\n", "\n", - "3. Renaming functions during import: You can also rename functions during import using the as keyword. This is useful if you want to use a shorter or more descriptive name for the function in your code. For example:\n", + "3. Cambiar el nombre de las funciones durante la importación: también puede cambiar el nombre de las funciones durante la importación utilizando la palabra clave as. Esto es útil si desea utilizar un nombre más corto o más descriptivo para la función en su código. Por ejemplo:\n", "\n", - "```python\n", - "from function_file import function_name as f\n", + "```pitón\n", + "desde archivo_función importar nombre_función como f\n", "\n", - "f.function_name(arguments)\n", + "f.nombre_función(argumentos)\n", "```\n", "\n", - "Regardless of which method you choose, make sure that the functions.py file is in the same directory as your Jupyter Notebook, or else specify the path to the file in the import statement or by using `sys.path`.\n", - "\n", + "Independientemente del método que elija, asegúrese de que el archivo funciones.py esté en el mismo directorio que su Jupyter Notebook, o especifique la ruta al archivo en la declaración de importación o usando `sys.path`.\n", "You can find examples on how to import Python files into jupyter notebook here: \n", "- https://medium.com/cold-brew-code/a-quick-guide-to-understanding-pythons-import-statement-505eea2d601f\n", "- https://www.geeksforgeeks.org/absolute-and-relative-imports-in-python/\n", @@ -260,12 +440,12 @@ "id": "14f222c5-e7bb-4626-b45c-bd735001f768", "metadata": {}, "source": [ - "To ensure that any changes made to the Python file are reflected in the Jupyter Notebook upon import, we need to use an IPython extension that allows for automatic reloading of modules. Without this extension, changes made to the file won't be reloaded or refreshed in the notebook upon import.\n", + "Para garantizar que cualquier cambio realizado en el archivo Python se refleje en Jupyter Notebook al momento de la importación, debemos usar una extensión IPython que permita la recarga automática de módulos. Sin esta extensión, los cambios realizados en el archivo no se recargarán ni actualizarán en el cuaderno al importarlo.\n", "\n", - "For that, we will include the following code:\n", - "```python\n", - "%load_ext autoreload\n", - "%autoreload 2 \n", + "Para eso, incluiremos el siguiente código:\n", + "```pitón\n", + "%load_ext recarga automática\n", + "% recarga automática 2\n", "```\n", "\n", "You can read more about this here: https://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html" @@ -291,14 +471,13 @@ "metadata": {}, "source": [ "## Bonus: recursive functions\n", + "La secuencia de Fibonacci es una secuencia matemática que aparece en diversos campos, incluidos la naturaleza, las finanzas y la informática. Comienza con 0 y 1, y cada número posterior es la suma de los dos números anteriores. La secuencia es la siguiente: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, etc.\n", "\n", - "The Fibonacci sequence is a mathematical sequence that appears in various fields, including nature, finance, and computer science. It starts with 0 and 1, and each subsequent number is the sum of the two preceding numbers. The sequence goes like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on.\n", - "\n", - "Write a Python function that uses recursion to compute the Fibonacci sequence up to a given number n.\n", + "Escriba una función de Python que utilice la recursividad para calcular la secuencia de Fibonacci hasta un número dado n.\n", "\n", - "To accomplish this, create a function that calculates the Fibonacci number for a given input. For example, the 10th Fibonacci number is 55.\n", - "Then create another function that generates a list of Fibonacci numbers from 0 to n.\n", - "Test your function by calling it with different input parameters." + "Para lograr esto, cree una función que calcule el número de Fibonacci para una entrada determinada. Por ejemplo, el décimo número de Fibonacci es 55.\n", + "Luego crea otra función que genere una lista de números de Fibonacci del 0 al n.\n", + "Pruebe su función llamándola con diferentes parámetros de entrada." ] }, { @@ -326,7 +505,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "base", "language": "python", "name": "python3" }, @@ -340,7 +519,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.14.6" } }, "nbformat": 4,