From f6c6e209978a6fb7aa857b32d7a180ca811bac2b Mon Sep 17 00:00:00 2001 From: Jose Mora <109150320+josemoracard@users.noreply.github.com> Date: Wed, 6 Mar 2024 12:20:33 +0000 Subject: [PATCH] fixed text problems.ipynb, solutions.ipynb --- notebook/problems.es.ipynb | 2 +- notebook/problems.ipynb | 2 +- notebook/solutions.ipynb | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/notebook/problems.es.ipynb b/notebook/problems.es.ipynb index 565cbde7..dad0c74f 100644 --- a/notebook/problems.es.ipynb +++ b/notebook/problems.es.ipynb @@ -1 +1 @@ -{"cells":[{"attachments":{},"cell_type":"markdown","id":"27b09e13","metadata":{},"source":["# Problemas de optimización de algoritmos"]},{"attachments":{},"cell_type":"markdown","id":"ed05e9bf","metadata":{},"source":["## Ejercicio 1\n","### Optimización de código para procesamiento de texto\n","\n","Se te ha entregado un código de procesamiento de texto que realiza las siguientes operaciones:\n","\n","1. Convierte todo el texto a minúsculas.\n","2. Elimina los signos de puntuación.\n","3. Cuenta la frecuencia de cada palabra.\n","4. Muestra las 5 palabras mas comunes.\n","\n","El código funciona, pero es ineficiente y puede optimizarse. Tu tarea es identificar las áreas que pueden ser mejoradas y reescribir esas partes para hacer el código mas eficiente y legible.\n"]},{"cell_type":"code","execution_count":1,"id":"8467465b","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["'the': 5 times\n","'of': 3 times\n","'in': 2 times\n","'a': 2 times\n","'she': 2 times\n"]}],"source":["import string\n","\n","def process_text(text):\n"," # Texto a minuscula\n"," text = text.lower()\n","\n"," # Eliminación de puntuaciones\n"," for p in string.punctuation:\n"," text = text.replace(p, \"\")\n","\n"," # Split text into words\n"," words = text.split()\n","\n"," # Conteo de frecuencias\n"," frequencies = {}\n"," for w in words:\n"," if w in frequencies:\n"," frequencies[w] += 1\n"," else:\n"," frequencies[w] = 1\n","\n"," sorted_frequencies = sorted(frequencies.items(), key = lambda x: x[1], reverse = True)\n","\n"," # Obtener las 5 palabras más comunes\n"," top_5 = sorted_frequencies[:5]\n"," \n"," for w, frequency in top_5:\n"," print(f\"'{w}': {frequency} times\")\n","\n","text = \"\"\"\n"," In the heart of the city, Emily discovered a quaint little café, hidden away from the bustling streets. \n"," The aroma of freshly baked pastries wafted through the air, drawing in passersby. As she sipped on her latte, \n"," she noticed an old bookshelf filled with classics, creating a cozy atmosphere that made her lose track of time.\n","\"\"\"\n","process_text(text)"]},{"cell_type":"markdown","id":"29040779","metadata":{},"source":["Puntos a optimizar:\n","\n","1. **Eliminar los signos de puntuación**: Usar `replace` en un ciclo puede ser ineficiente, especialmente con textos largos. Busca una formas eficiente de eliminar los signos de puntuación.\n","2. **Contador de frecuencia**: El código verifica la existencia de cada palabra en el diccionario y luego actualiza su cuenta. Esto puede hacerse mas eficientemente con ciertas estructuras de datos en Python.\n","3. **Ordenar y seleccionar:** Considera si hay una forma mas directa o efectiva de obtener las 5 palabras mas frecuentes sin ordenar todas las palabras.\n","4. **Modularidad**: Divide el código en funciones mas pequeñas para que cada una puede realizar una tarea específica. Esto no solo optimizará el desempeño, sino también hará el código mas legible y mantenible."]},{"cell_type":"code","execution_count":2,"id":"57cd6641","metadata":{},"outputs":[],"source":["# TODO"]},{"attachments":{},"cell_type":"markdown","id":"011996bc","metadata":{},"source":["## Ejercicio 2\n","### Optimización de código para procesamiento de listas\n","\n","Se te ha dado el siguiente código que realiza operaciones en una lista de números para:\n","\n","1. Filtrar los números pares.\n","2. Duplicar cada número.\n","3. Sumar todos los números.\n","4. Verificar si el resultado es un número primo.\n","\n","El código entregado logra los objetivos, pero puede ser ineficiente. Tu tarea es identificar y mejorar las partes de ese código para mejorar su eficiencia."]},{"cell_type":"code","execution_count":3,"id":"783d03a0","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["Result: 60, ¿Prime? No\n"]}],"source":["import math\n","\n","def is_prime(n):\n"," if n <= 1:\n"," return False\n"," for i in range(2, int(math.sqrt(n)) + 1):\n"," if n % i == 0:\n"," return False\n"," return True\n","\n","def process_list(list_):\n"," filtered_list = []\n"," for num in list_:\n"," if num % 2 == 0:\n"," filtered_list.append(num)\n"," \n"," duplicate_list = []\n"," for num in filtered_list:\n"," duplicate_list.append(num * 2)\n"," \n"," sum = 0\n"," for num in duplicate_list:\n"," sum += num\n","\n"," prime = is_prime(sum)\n"," \n"," return sum, prime\n","\n","list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n","result, result_prime = process_list(list_)\n","print(f\"Result: {result}, ¿Prime? {'Yes' if result_prime else 'No'}\")"]},{"cell_type":"markdown","id":"128d564e","metadata":{},"source":["Puntos a optimizar:\n","\n","1. **Filtrar las números**: El código recorre la lista original para filtrar los números pares. Considera una forma mas eficiente de filtrar la lista.\n","2. **Duplicación**: La lista es atravesada varias veces. ¿Hay alguna manera de hacer esto mas eficientemente?\n","3. **Suma**: Los números en la lista se suman a traves de un bucle. Python trae incluidas unas funciones que pueden optimizar esto.\n","4. **Función `is_prime`**: Aunque ésta función es relativamente eficiente, investiga si hay maneras de hacerla aun más rápida.\n","5. **Modularidad**: Considera dividir el código en funciones más pequeñas, cada una enfocada en una tarea específica."]},{"cell_type":"code","execution_count":4,"id":"f40e35d6","metadata":{},"outputs":[],"source":["# TODO"]},{"attachments":{},"cell_type":"markdown","id":"1af70806","metadata":{},"source":["Ambos ejercicios ayudarán a mejorar tu habilidad de optimizar el desempeño del código y te darán un mejor entendimiento de como las diferentes estructuras de datos y técnicas de programación pueden afectar la eficiencia de tu código."]}],"metadata":{"interpreter":{"hash":"9248718ffe6ce6938b217e69dbcc175ea21f4c6b28a317e96c05334edae734bb"},"kernelspec":{"display_name":"Python 3 (ipykernel)","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"}},"nbformat":4,"nbformat_minor":5} +{"cells":[{"attachments":{},"cell_type":"markdown","id":"27b09e13","metadata":{},"source":["# Problemas de optimización de algoritmos"]},{"attachments":{},"cell_type":"markdown","id":"ed05e9bf","metadata":{},"source":["## Ejercicio 1\n","### Optimización de código para procesamiento de texto\n","\n","Se te ha entregado un código de procesamiento de texto que realiza las siguientes operaciones:\n","\n","1. Convierte todo el texto a minúsculas.\n","2. Elimina los signos de puntuación.\n","3. Cuenta la frecuencia de cada palabra.\n","4. Muestra las 5 palabras más comunes.\n","\n","El código funciona, pero es ineficiente y puede optimizarse. Tu tarea es identificar las áreas que pueden ser mejoradas y reescribir esas partes para hacer el código más eficiente y legible."]},{"cell_type":"code","execution_count":1,"id":"8467465b","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["'the': 5 times\n","'of': 3 times\n","'in': 2 times\n","'a': 2 times\n","'she': 2 times\n"]}],"source":["import string\n","\n","def process_text(text):\n"," # Texto a minúscula\n"," text = text.lower()\n","\n"," # Eliminación de puntuaciones\n"," for p in string.punctuation:\n"," text = text.replace(p, \"\")\n","\n"," # Dividir el texto en palabras\n"," words = text.split()\n","\n"," # Conteo de frecuencias\n"," frequencies = {}\n"," for w in words:\n"," if w in frequencies:\n"," frequencies[w] += 1\n"," else:\n"," frequencies[w] = 1\n","\n"," sorted_frequencies = sorted(frequencies.items(), key = lambda x: x[1], reverse = True)\n","\n"," # Obtener las 5 palabras más comunes\n"," top_5 = sorted_frequencies[:5]\n"," \n"," for w, frequency in top_5:\n"," print(f\"'{w}': {frequency} times\")\n","\n","text = \"\"\"\n"," In the heart of the city, Emily discovered a quaint little café, hidden away from the bustling streets. \n"," The aroma of freshly baked pastries wafted through the air, drawing in passersby. As she sipped on her latte, \n"," she noticed an old bookshelf filled with classics, creating a cozy atmosphere that made her lose track of time.\n","\"\"\"\n","process_text(text)"]},{"cell_type":"markdown","id":"29040779","metadata":{},"source":["Puntos a optimizar:\n","\n","1. **Eliminar los signos de puntuación**: Usar `replace` en un ciclo puede ser ineficiente, especialmente con textos largos. Busca una forma eficiente de eliminar los signos de puntuación.\n","2. **Contador de frecuencia**: El código verifica la existencia de cada palabra en el diccionario y luego actualiza su cuenta. Esto puede hacerse más eficientemente con ciertas estructuras de datos en Python.\n","3. **Ordenar y seleccionar:** Considera si hay una forma más directa o efectiva de obtener las 5 palabras más frecuentes sin ordenar todas las palabras.\n","4. **Modularidad**: Divide el código en funciones más pequeñas para que cada una puede realizar una tarea específica. Esto no solo optimizará el desempeño, sino también hará el código más legible y mantenible."]},{"cell_type":"code","execution_count":2,"id":"57cd6641","metadata":{},"outputs":[],"source":["# TODO"]},{"attachments":{},"cell_type":"markdown","id":"011996bc","metadata":{},"source":["## Ejercicio 2\n","### Optimización de código para procesamiento de listas\n","\n","Se te ha dado el siguiente código que realiza operaciones en una lista de números para:\n","\n","1. Filtrar los números pares.\n","2. Duplicar cada número.\n","3. Sumar todos los números.\n","4. Verificar si el resultado es un número primo.\n","\n","El código entregado logra los objetivos, pero puede ser ineficiente. Tu tarea es identificar y mejorar las partes de ese código para mejorar su eficiencia."]},{"cell_type":"code","execution_count":3,"id":"783d03a0","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["Result: 60, ¿Prime? No\n"]}],"source":["import math\n","\n","def is_prime(n):\n"," # Chequea si el resultado es número primo\n"," if n <= 1:\n"," return False\n"," for i in range(2, int(math.sqrt(n)) + 1):\n"," if n % i == 0:\n"," return False\n"," return True\n","\n","def process_list(list_):\n"," # Filtra los números pares\n"," filtered_list = []\n"," for num in list_:\n"," if num % 2 == 0:\n"," filtered_list.append(num)\n"," \n"," # Duplica cada número\n"," duplicate_list = []\n"," for num in filtered_list:\n"," duplicate_list.append(num * 2)\n","\n"," # Suma todos los números \n"," sum = 0\n"," for num in duplicate_list:\n"," sum += num\n","\n"," prime = is_prime(sum)\n"," \n"," return sum, prime\n","\n","list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n","result, result_prime = process_list(list_)\n","print(f\"Result: {result}, ¿Prime? {'Yes' if result_prime else 'No'}\")"]},{"cell_type":"markdown","id":"128d564e","metadata":{},"source":["Puntos a optimizar:\n","\n","1. **Filtrar los números**: El código recorre la lista original para filtrar los números pares. Considera una forma más eficiente de filtrar la lista.\n","2. **Duplicación**: La lista es iterada varias veces. ¿Hay alguna manera de hacer esto más eficientemente?\n","3. **Suma**: Los números en la lista se suman a través de un bucle. Python trae incluidas funciones que pueden optimizar esto.\n","4. **Función `is_prime`**: Aunque esta función es relativamente eficiente, investiga si hay maneras de hacerla aún más rápida.\n","5. **Modularidad**: Considera dividir el código en funciones más pequeñas, cada una enfocada en una tarea específica."]},{"cell_type":"code","execution_count":4,"id":"f40e35d6","metadata":{},"outputs":[],"source":["# TODO"]},{"attachments":{},"cell_type":"markdown","id":"1af70806","metadata":{},"source":["Ambos ejercicios ayudarán a mejorar tu habilidad de optimizar el desempeño del código y te darán un mejor entendimiento de como las diferentes estructuras de datos y técnicas de programación pueden afectar la eficiencia de tu código."]}],"metadata":{"interpreter":{"hash":"9248718ffe6ce6938b217e69dbcc175ea21f4c6b28a317e96c05334edae734bb"},"kernelspec":{"display_name":"Python 3 (ipykernel)","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"}},"nbformat":4,"nbformat_minor":5} diff --git a/notebook/problems.ipynb b/notebook/problems.ipynb index 49df804e..0cbc5274 100644 --- a/notebook/problems.ipynb +++ b/notebook/problems.ipynb @@ -1 +1 @@ -{"cells":[{"attachments":{},"cell_type":"markdown","id":"27b09e13","metadata":{},"source":["# Optimization of Algorithms problems"]},{"attachments":{},"cell_type":"markdown","id":"ed05e9bf","metadata":{},"source":["## Exercise 1\n","### Code Optimization for Text Processing\n","\n","You are provided with a text processing code to perform the following operations:\n","\n","1. Convert all text to lowercase.\n","2. Remove punctuation marks.\n","3. Count the frequency of each word.\n","4. Show the 5 most common words.\n","\n","The code works, but it is inefficient and can be optimized. Your task is to identify areas that can be improved and rewrite those parts to make the code more efficient and readable."]},{"cell_type":"code","execution_count":1,"id":"8467465b","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["'the': 5 times\n","'of': 3 times\n","'in': 2 times\n","'a': 2 times\n","'she': 2 times\n"]}],"source":["import string\n","\n","def process_text(text):\n"," # Text to lowercase\n"," text = text.lower()\n","\n"," # Remove punctuation\n"," for p in string.punctuation:\n"," text = text.replace(p, \"\")\n","\n"," # Split text into words\n"," words = text.split()\n","\n"," # Count frecuencies\n"," frequencies = {}\n"," for w in words:\n"," if w in frequencies:\n"," frequencies[w] += 1\n"," else:\n"," frequencies[w] = 1\n","\n"," sorted_frequencies = sorted(frequencies.items(), key = lambda x: x[1], reverse = True)\n","\n"," # Get 5 most-common words\n"," top_5 = sorted_frequencies[:5]\n"," \n"," for w, frequency in top_5:\n"," print(f\"'{w}': {frequency} times\")\n","\n","text = \"\"\"\n"," In the heart of the city, Emily discovered a quaint little café, hidden away from the bustling streets. \n"," The aroma of freshly baked pastries wafted through the air, drawing in passersby. As she sipped on her latte, \n"," she noticed an old bookshelf filled with classics, creating a cozy atmosphere that made her lose track of time.\n","\"\"\"\n","process_text(text)"]},{"cell_type":"markdown","id":"29040779","metadata":{},"source":["Points to optimize:\n","\n","1. **Removal of punctuation marks**: Using `replace` in a loop can be inefficient, especially with long texts. Look for a more efficient way to remove punctuation marks.\n","2. **Frequency count**: The code checks for the existence of each word in the dictionary and then updates its count. This can be done more efficiently with certain data structures in Python.\n","3. **Sort and select:** Consider if there is a more direct or efficient way to get the 5 most frequent words without sorting all the words.\n","4. **Modularity**: Break the code into smaller functions so that each one performs a specific task. This will not only optimize performance, but also make the code more readable and maintainable."]},{"cell_type":"code","execution_count":2,"id":"57cd6641","metadata":{},"outputs":[],"source":["# TODO"]},{"attachments":{},"cell_type":"markdown","id":"011996bc","metadata":{},"source":["## Exercise 2\n","### Code Optimization for List Processing\n","\n","You have been given a code that performs operations on a list of numbers for:\n","\n","1. Filter out even numbers.\n","2. Duplicate each number.\n","3. Add all numbers.\n","4. Check if the result is a prime number.\n","\n","The code provided achieves its goal, but it may be inefficient. Your task is to identify and improve the parts of the code to increase its efficiency."]},{"cell_type":"code","execution_count":3,"id":"783d03a0","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["Result: 60, ¿Prime? No\n"]}],"source":["import math\n","\n","def is_prime(n):\n"," if n <= 1:\n"," return False\n"," for i in range(2, int(math.sqrt(n)) + 1):\n"," if n % i == 0:\n"," return False\n"," return True\n","\n","def process_list(list_):\n"," filtered_list = []\n"," for num in list_:\n"," if num % 2 == 0:\n"," filtered_list.append(num)\n"," \n"," duplicate_list = []\n"," for num in filtered_list:\n"," duplicate_list.append(num * 2)\n"," \n"," sum = 0\n"," for num in duplicate_list:\n"," sum += num\n","\n"," prime = is_prime(sum)\n"," \n"," return sum, prime\n","\n","list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n","result, result_prime = process_list(list_)\n","print(f\"Result: {result}, ¿Prime? {'Yes' if result_prime else 'No'}\")"]},{"cell_type":"markdown","id":"128d564e","metadata":{},"source":["Points to optimize:\n","\n","1. **Filter numbers**: The code goes through the original list to filter out even numbers. Consider a more efficient way to filter the list.\n","2. **Duplication**: The list is traversed multiple times. Is there a way to do this more efficiently?\n","3. **Summing**: The numbers in a list are summed through a loop. Python has built-in functions that can optimize this.\n","4. **Function `is_prime`**: While this function is relatively efficient, investigate if there are ways to make it even faster.\n","5. **Modularity**: Consider breaking the code into smaller functions, each focused on a specific task."]},{"cell_type":"code","execution_count":4,"id":"f40e35d6","metadata":{},"outputs":[],"source":["# TODO"]},{"attachments":{},"cell_type":"markdown","id":"1af70806","metadata":{},"source":["Both exercises will help you improve your code performance optimization skills and give you a better understanding of how different data structures and programming techniques can affect the efficiency of your code."]}],"metadata":{"interpreter":{"hash":"9248718ffe6ce6938b217e69dbcc175ea21f4c6b28a317e96c05334edae734bb"},"kernelspec":{"display_name":"Python 3 (ipykernel)","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"}},"nbformat":4,"nbformat_minor":5} +{"cells":[{"attachments":{},"cell_type":"markdown","id":"27b09e13","metadata":{},"source":["# Optimization of Algorithms problems"]},{"attachments":{},"cell_type":"markdown","id":"ed05e9bf","metadata":{},"source":["## Exercise 1\n","### Code Optimization for Text Processing\n","\n","You are provided with a text processing code to perform the following operations:\n","\n","1. Convert all text to lowercase.\n","2. Remove punctuation marks.\n","3. Count the frequency of each word.\n","4. Show the 5 most common words.\n","\n","The code works, but it is inefficient and can be optimized. Your task is to identify areas that can be improved and rewrite those parts to make the code more efficient and readable."]},{"cell_type":"code","execution_count":1,"id":"8467465b","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["'the': 5 times\n","'of': 3 times\n","'in': 2 times\n","'a': 2 times\n","'she': 2 times\n"]}],"source":["import string\n","\n","def process_text(text):\n"," # Text to lowercase\n"," text = text.lower()\n","\n"," # Remove punctuation\n"," for p in string.punctuation:\n"," text = text.replace(p, \"\")\n","\n"," # Split text into words\n"," words = text.split()\n","\n"," # Count frecuencies\n"," frequencies = {}\n"," for w in words:\n"," if w in frequencies:\n"," frequencies[w] += 1\n"," else:\n"," frequencies[w] = 1\n","\n"," sorted_frequencies = sorted(frequencies.items(), key = lambda x: x[1], reverse = True)\n","\n"," # Get 5 most common words\n"," top_5 = sorted_frequencies[:5]\n"," \n"," for w, frequency in top_5:\n"," print(f\"'{w}': {frequency} times\")\n","\n","text = \"\"\"\n"," In the heart of the city, Emily discovered a quaint little café, hidden away from the bustling streets. \n"," The aroma of freshly baked pastries wafted through the air, drawing in passersby. As she sipped on her latte, \n"," she noticed an old bookshelf filled with classics, creating a cozy atmosphere that made her lose track of time.\n","\"\"\"\n","process_text(text)"]},{"cell_type":"markdown","id":"29040779","metadata":{},"source":["Points to optimize:\n","\n","1. **Removal of punctuation marks**: Using `replace` in a loop can be inefficient, especially with long texts. Look for a more efficient way to remove punctuation marks.\n","2. **Frequency count**: The code checks for the existence of each word in the dictionary and then updates its count. This can be done more efficiently with certain data structures in Python.\n","3. **Sort and select:** Consider if there is a more direct or efficient way to get the 5 most frequent words without sorting all the words.\n","4. **Modularity**: Break the code into smaller functions so that each one performs a specific task. This will not only optimize performance, but also make the code more readable and maintainable."]},{"cell_type":"code","execution_count":2,"id":"57cd6641","metadata":{},"outputs":[],"source":["# TODO"]},{"attachments":{},"cell_type":"markdown","id":"011996bc","metadata":{},"source":["## Exercise 2\n","### Code Optimization for List Processing\n","\n","You have been given a code that performs operations on a list of numbers to:\n","\n","1. Filter out even numbers.\n","2. Duplicate each number.\n","3. Add all numbers.\n","4. Check if the result is a prime number.\n","\n","The code provided achieves its goal, but it may be inefficient. Your task is to identify and improve parts of the code to increase its efficiency."]},{"cell_type":"code","execution_count":3,"id":"783d03a0","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["Result: 60, ¿Prime? No\n"]}],"source":["import math\n","\n","def is_prime(n):\n"," # Check if the result is a prime number\n"," if n <= 1:\n"," return False\n"," for i in range(2, int(math.sqrt(n)) + 1):\n"," if n % i == 0:\n"," return False\n"," return True\n","\n","def process_list(list_):\n"," # Filter out even numbers\n"," filtered_list = []\n"," for num in list_:\n"," if num % 2 == 0:\n"," filtered_list.append(num)\n","\n"," # Duplicate each number \n"," duplicate_list = []\n"," for num in filtered_list:\n"," duplicate_list.append(num * 2)\n","\n"," # Add all numbers \n"," sum = 0\n"," for num in duplicate_list:\n"," sum += num\n","\n"," prime = is_prime(sum)\n"," \n"," return sum, prime\n","\n","list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n","result, result_prime = process_list(list_)\n","print(f\"Result: {result}, ¿Prime? {'Yes' if result_prime else 'No'}\")"]},{"cell_type":"markdown","id":"128d564e","metadata":{},"source":["Points to optimize:\n","\n","1. **Filter numbers**: The code goes through the original list to filter out even numbers. Consider a more efficient way to filter the list.\n","2. **Duplication**: The list is traversed multiple times. Is there a way to do this more efficiently?\n","3. **Summing**: The numbers in a list are summed through a loop. Python has built-in functions that can optimize this.\n","4. **Function `is_prime`**: While this function is relatively efficient, investigate if there are ways to make it even faster.\n","5. **Modularity**: Consider breaking the code into smaller functions, each focused on a specific task."]},{"cell_type":"code","execution_count":4,"id":"f40e35d6","metadata":{},"outputs":[],"source":["# TODO"]},{"attachments":{},"cell_type":"markdown","id":"1af70806","metadata":{},"source":["Both exercises will help you improve your code performance optimization skills and give you a better understanding of how different data structures and programming techniques can affect the efficiency of your code."]}],"metadata":{"interpreter":{"hash":"9248718ffe6ce6938b217e69dbcc175ea21f4c6b28a317e96c05334edae734bb"},"kernelspec":{"display_name":"Python 3 (ipykernel)","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"}},"nbformat":4,"nbformat_minor":5} diff --git a/notebook/solutions.ipynb b/notebook/solutions.ipynb index a7e0e947..4bbac311 100644 --- a/notebook/solutions.ipynb +++ b/notebook/solutions.ipynb @@ -1 +1 @@ -{"cells":[{"attachments":{},"cell_type":"markdown","id":"27b09e13","metadata":{},"source":["# Optimization of Algorithms solutions"]},{"attachments":{},"cell_type":"markdown","id":"ed05e9bf","metadata":{},"source":["## Exercise 1"]},{"cell_type":"code","execution_count":1,"id":"9ac23620","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["'the': 5 veces\n","'of': 3 veces\n","'in': 2 veces\n","'a': 2 veces\n","'she': 2 veces\n"]}],"source":["from collections import Counter\n","import string\n","\n","def remove_punctuation(text):\n"," translator = str.maketrans(\"\", \"\", string.punctuation)\n"," return text.translate(translator)\n","\n","def count_words(text):\n"," # Split text into words\n"," palabras = text.split()\n","\n"," return Counter(palabras)\n","\n","def get_most_common(frequencies, n = 5):\n"," return frequencies.most_common(n)\n","\n","def process_text(text):\n"," # Text to lowercase\n"," text = text.lower()\n","\n"," # Remove punctuation\n"," text = remove_punctuation(text)\n"," \n"," # Count frecuencies\n"," frequencies = count_words(text)\n"," \n"," top_5 = get_most_common(frequencies)\n"," \n"," for w, frequency in top_5:\n"," print(f\"'{w}': {frequency} veces\")\n","\n","text = \"\"\"\n"," In the heart of the city, Emily discovered a quaint little café, hidden away from the bustling streets. \n"," The aroma of freshly baked pastries wafted through the air, drawing in passersby. As she sipped on her latte, \n"," she noticed an old bookshelf filled with classics, creating a cozy atmosphere that made her lose track of time.\n","\"\"\"\n","process_text(text)"]},{"attachments":{},"cell_type":"markdown","id":"ca62bab1","metadata":{},"source":["## Exercise 2"]},{"cell_type":"code","execution_count":2,"id":"34e63cf1","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["Result: 60, ¿Prime? No\n"]}],"source":["def is_prime(n):\n"," if (n <= 1):\n"," return False\n"," if (n <= 3):\n"," return True\n"," if (n % 2 == 0) or (n % 3 == 0):\n"," return False\n"," i = 5\n"," while ((i * i) <= n):\n"," if (n % i == 0) or (n % (i + 2) == 0):\n"," return False\n"," i += 6\n"," return True\n","\n","def filter_duplicate(list_):\n"," # Filter and duplicate numbers in a single step\n"," return [num * 2 for num in list_ if num % 2 == 0]\n","\n","def process_list(list_):\n"," duplicate_list = filter_duplicate(list_)\n"," \n"," # Compute sum\n"," sum_ = sum(duplicate_list)\n"," prime = is_prime(sum_)\n"," \n"," return sum_, prime\n","\n","list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n","result, result_prime = process_list(list_)\n","print(f\"Result: {result}, ¿Prime? {'Yes' if result_prime else 'No'}\")"]}],"metadata":{"interpreter":{"hash":"9248718ffe6ce6938b217e69dbcc175ea21f4c6b28a317e96c05334edae734bb"},"kernelspec":{"display_name":"Python 3.9.12 ('ML-BOOTCAMP')","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"},"vscode":{"interpreter":{"hash":"31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"}}},"nbformat":4,"nbformat_minor":5} +{"cells":[{"attachments":{},"cell_type":"markdown","id":"27b09e13","metadata":{},"source":["# Optimization of Algorithms solutions"]},{"attachments":{},"cell_type":"markdown","id":"ed05e9bf","metadata":{},"source":["## Exercise 1"]},{"cell_type":"code","execution_count":null,"id":"9ac23620","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["'the': 5 veces\n","'of': 3 veces\n","'in': 2 veces\n","'a': 2 veces\n","'she': 2 veces\n"]}],"source":["from collections import Counter\n","import string\n","\n","def remove_punctuation(text):\n"," translator = str.maketrans(\"\", \"\", string.punctuation)\n"," return text.translate(translator)\n","\n","def count_words(text):\n"," # Split text into words\n"," words = text.split()\n","\n"," return Counter(words)\n","\n","def get_most_common(frequencies, n = 5):\n"," return frequencies.most_common(n)\n","\n","def process_text(text):\n"," # Text to lowercase\n"," text = text.lower()\n","\n"," # Remove punctuation\n"," text = remove_punctuation(text)\n"," \n"," # Count frecuencies\n"," frequencies = count_words(text)\n"," \n"," top_5 = get_most_common(frequencies)\n"," \n"," for w, frequency in top_5:\n"," print(f\"'{w}': {frequency} times\")\n","\n","text = \"\"\"\n"," In the heart of the city, Emily discovered a quaint little café, hidden away from the bustling streets. \n"," The aroma of freshly baked pastries wafted through the air, drawing in passersby. As she sipped on her latte, \n"," she noticed an old bookshelf filled with classics, creating a cozy atmosphere that made her lose track of time.\n","\"\"\"\n","process_text(text)"]},{"attachments":{},"cell_type":"markdown","id":"ca62bab1","metadata":{},"source":["## Exercise 2"]},{"cell_type":"code","execution_count":null,"id":"34e63cf1","metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["Result: 60, ¿Prime? No\n"]}],"source":["def is_prime(n):\n"," # Check if the result is a prime number\n"," if (n <= 1):\n"," return False\n"," if (n <= 3):\n"," return True\n"," if (n % 2 == 0) or (n % 3 == 0):\n"," return False\n"," i = 5\n"," while ((i * i) <= n):\n"," if (n % i == 0) or (n % (i + 2) == 0):\n"," return False\n"," i += 6\n"," return True\n","\n","def filter_duplicate(list_):\n"," # Filter and duplicate numbers in a single step\n"," return [num * 2 for num in list_ if num % 2 == 0]\n","\n","def process_list(list_):\n"," duplicate_list = filter_duplicate(list_)\n"," \n"," # Compute sum\n"," sum_ = sum(duplicate_list)\n"," prime = is_prime(sum_)\n"," \n"," return sum_, prime\n","\n","list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n","result, result_prime = process_list(list_)\n","print(f\"Result: {result}, ¿Prime? {'Yes' if result_prime else 'No'}\")"]}],"metadata":{"interpreter":{"hash":"9248718ffe6ce6938b217e69dbcc175ea21f4c6b28a317e96c05334edae734bb"},"kernelspec":{"display_name":"Python 3.9.12 ('ML-BOOTCAMP')","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"},"vscode":{"interpreter":{"hash":"31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"}}},"nbformat":4,"nbformat_minor":5}