|
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} |
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "attachments": {}, |
| 5 | + "cell_type": "markdown", |
| 6 | + "id": "27b09e13", |
| 7 | + "metadata": {}, |
| 8 | + "source": [ |
| 9 | + "# Optimization of Algorithms problems" |
| 10 | + ] |
| 11 | + }, |
| 12 | + { |
| 13 | + "attachments": {}, |
| 14 | + "cell_type": "markdown", |
| 15 | + "id": "ed05e9bf", |
| 16 | + "metadata": {}, |
| 17 | + "source": [ |
| 18 | + "## Exercise 1\n", |
| 19 | + "### Code Optimization for Text Processing\n", |
| 20 | + "\n", |
| 21 | + "You are provided with a text processing code to perform the following operations:\n", |
| 22 | + "\n", |
| 23 | + "1. Convert all text to lowercase.\n", |
| 24 | + "2. Remove punctuation marks.\n", |
| 25 | + "3. Count the frequency of each word.\n", |
| 26 | + "4. Show the 5 most common words.\n", |
| 27 | + "\n", |
| 28 | + "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." |
| 29 | + ] |
| 30 | + }, |
| 31 | + { |
| 32 | + "cell_type": "code", |
| 33 | + "execution_count": 14, |
| 34 | + "id": "8467465b", |
| 35 | + "metadata": {}, |
| 36 | + "outputs": [ |
| 37 | + { |
| 38 | + "name": "stdout", |
| 39 | + "output_type": "stream", |
| 40 | + "text": [ |
| 41 | + "'the': 5 veces\n", |
| 42 | + "'of': 3 veces\n", |
| 43 | + "'in': 2 veces\n", |
| 44 | + "'a': 2 veces\n", |
| 45 | + "'she': 2 veces\n" |
| 46 | + ] |
| 47 | + } |
| 48 | + ], |
| 49 | + "source": [ |
| 50 | + "from collections import Counter\n", |
| 51 | + "import string\n", |
| 52 | + "\n", |
| 53 | + "def remove_punctuation(text):\n", |
| 54 | + " translator = str.maketrans(\"\", \"\", string.punctuation)\n", |
| 55 | + " return text.translate(translator)\n", |
| 56 | + "\n", |
| 57 | + "def count_words(text):\n", |
| 58 | + " # Split text into words\n", |
| 59 | + " palabras = text.split()\n", |
| 60 | + "\n", |
| 61 | + " return Counter(palabras)\n", |
| 62 | + "\n", |
| 63 | + "def get_most_common(frequencies, n = 5):\n", |
| 64 | + " return frequencies.most_common(n)\n", |
| 65 | + "\n", |
| 66 | + "def process_text(text):\n", |
| 67 | + " # Text to lowercase\n", |
| 68 | + " text = text.lower()\n", |
| 69 | + "\n", |
| 70 | + " # Remove punctuation\n", |
| 71 | + " text = remove_punctuation(text)\n", |
| 72 | + " \n", |
| 73 | + " # Count frecuencies\n", |
| 74 | + " frequencies = count_words(text)\n", |
| 75 | + " \n", |
| 76 | + " top_5 = get_most_common(frequencies)\n", |
| 77 | + " \n", |
| 78 | + " for w, frequency in top_5:\n", |
| 79 | + " print(f\"'{w}': {frequency} veces\")\n", |
| 80 | + "\n", |
| 81 | + "text = \"\"\"\n", |
| 82 | + " In the heart of the city, Emily discovered a quaint little café, hidden away from the bustling streets. \n", |
| 83 | + " The aroma of freshly baked pastries wafted through the air, drawing in passersby. As she sipped on her latte, \n", |
| 84 | + " she noticed an old bookshelf filled with classics, creating a cozy atmosphere that made her lose track of time.\n", |
| 85 | + "\"\"\"\n", |
| 86 | + "process_text(text)" |
| 87 | + ] |
| 88 | + }, |
| 89 | + { |
| 90 | + "cell_type": "markdown", |
| 91 | + "id": "29040779", |
| 92 | + "metadata": {}, |
| 93 | + "source": [ |
| 94 | + "Points to optimize:\n", |
| 95 | + "\n", |
| 96 | + "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", |
| 97 | + "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", |
| 98 | + "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", |
| 99 | + "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." |
| 100 | + ] |
| 101 | + }, |
| 102 | + { |
| 103 | + "cell_type": "code", |
| 104 | + "execution_count": 15, |
| 105 | + "id": "57cd6641", |
| 106 | + "metadata": {}, |
| 107 | + "outputs": [ |
| 108 | + { |
| 109 | + "name": "stdout", |
| 110 | + "output_type": "stream", |
| 111 | + "text": [ |
| 112 | + "[('the', 4), ('of', 3), ('a', 2), ('she', 2), ('her', 2)]\n" |
| 113 | + ] |
| 114 | + } |
| 115 | + ], |
| 116 | + "source": [ |
| 117 | + "from collections import Counter\n", |
| 118 | + "\n", |
| 119 | + "def lowercase(text: str) -> str:\n", |
| 120 | + " '''Takes text string, returns lowercased string.'''\n", |
| 121 | + "\n", |
| 122 | + " return text.lower()\n", |
| 123 | + "\n", |
| 124 | + "def remove_punctuation(text: str) -> str:\n", |
| 125 | + " '''Takes text string, removes common puncuation marks. returns string'''\n", |
| 126 | + "\n", |
| 127 | + " return ''.join([x for x in list(text) if x not in string.punctuation])\n", |
| 128 | + "\n", |
| 129 | + "def top_n(text: str, n: int) -> list:\n", |
| 130 | + " '''Takes text string and n, returns a list of tuples containing the top n most common \n", |
| 131 | + " words: (word, frequency).'''\n", |
| 132 | + "\n", |
| 133 | + " return Counter(text.split()).most_common(n)\n", |
| 134 | + "\n", |
| 135 | + "print(top_n(text, 5))" |
| 136 | + ] |
| 137 | + }, |
| 138 | + { |
| 139 | + "attachments": {}, |
| 140 | + "cell_type": "markdown", |
| 141 | + "id": "011996bc", |
| 142 | + "metadata": {}, |
| 143 | + "source": [ |
| 144 | + "## Exercise 2\n", |
| 145 | + "### Code Optimization for List Processing\n", |
| 146 | + "\n", |
| 147 | + "You have been given a code that performs operations on a list of numbers for:\n", |
| 148 | + "\n", |
| 149 | + "1. Filter out even numbers.\n", |
| 150 | + "2. Duplicate each number.\n", |
| 151 | + "3. Add all numbers.\n", |
| 152 | + "4. Check if the result is a prime number.\n", |
| 153 | + "\n", |
| 154 | + "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." |
| 155 | + ] |
| 156 | + }, |
| 157 | + { |
| 158 | + "cell_type": "code", |
| 159 | + "execution_count": 3, |
| 160 | + "id": "783d03a0", |
| 161 | + "metadata": {}, |
| 162 | + "outputs": [ |
| 163 | + { |
| 164 | + "name": "stdout", |
| 165 | + "output_type": "stream", |
| 166 | + "text": [ |
| 167 | + "Result: 60, ¿Prime? No\n" |
| 168 | + ] |
| 169 | + } |
| 170 | + ], |
| 171 | + "source": [ |
| 172 | + "import math\n", |
| 173 | + "\n", |
| 174 | + "def is_prime(n):\n", |
| 175 | + " if n <= 1:\n", |
| 176 | + " return False\n", |
| 177 | + " for i in range(2, int(math.sqrt(n)) + 1):\n", |
| 178 | + " if n % i == 0:\n", |
| 179 | + " return False\n", |
| 180 | + " return True\n", |
| 181 | + "\n", |
| 182 | + "def process_list(list_):\n", |
| 183 | + " filtered_list = []\n", |
| 184 | + " for num in list_:\n", |
| 185 | + " if num % 2 == 0:\n", |
| 186 | + " filtered_list.append(num)\n", |
| 187 | + " \n", |
| 188 | + " duplicate_list = []\n", |
| 189 | + " for num in filtered_list:\n", |
| 190 | + " duplicate_list.append(num * 2)\n", |
| 191 | + " \n", |
| 192 | + " sum = 0\n", |
| 193 | + " for num in duplicate_list:\n", |
| 194 | + " sum += num\n", |
| 195 | + "\n", |
| 196 | + " prime = is_prime(sum)\n", |
| 197 | + " \n", |
| 198 | + " return sum, prime\n", |
| 199 | + "\n", |
| 200 | + "list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", |
| 201 | + "result, result_prime = process_list(list_)\n", |
| 202 | + "print(f\"Result: {result}, ¿Prime? {'Yes' if result_prime else 'No'}\")" |
| 203 | + ] |
| 204 | + }, |
| 205 | + { |
| 206 | + "cell_type": "markdown", |
| 207 | + "id": "128d564e", |
| 208 | + "metadata": {}, |
| 209 | + "source": [ |
| 210 | + "Points to optimize:\n", |
| 211 | + "\n", |
| 212 | + "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", |
| 213 | + "2. **Duplication**: The list is traversed multiple times. Is there a way to do this more efficiently?\n", |
| 214 | + "3. **Summing**: The numbers in a list are summed through a loop. Python has built-in functions that can optimize this.\n", |
| 215 | + "4. **Function `is_prime`**: While this function is relatively efficient, investigate if there are ways to make it even faster.\n", |
| 216 | + "5. **Modularity**: Consider breaking the code into smaller functions, each focused on a specific task." |
| 217 | + ] |
| 218 | + }, |
| 219 | + { |
| 220 | + "cell_type": "code", |
| 221 | + "execution_count": 4, |
| 222 | + "id": "f40e35d6", |
| 223 | + "metadata": {}, |
| 224 | + "outputs": [], |
| 225 | + "source": [ |
| 226 | + "# TODO" |
| 227 | + ] |
| 228 | + }, |
| 229 | + { |
| 230 | + "attachments": {}, |
| 231 | + "cell_type": "markdown", |
| 232 | + "id": "1af70806", |
| 233 | + "metadata": {}, |
| 234 | + "source": [ |
| 235 | + "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." |
| 236 | + ] |
| 237 | + } |
| 238 | + ], |
| 239 | + "metadata": { |
| 240 | + "kernelspec": { |
| 241 | + "display_name": "Python 3", |
| 242 | + "language": "python", |
| 243 | + "name": "python3" |
| 244 | + }, |
| 245 | + "language_info": { |
| 246 | + "codemirror_mode": { |
| 247 | + "name": "ipython", |
| 248 | + "version": 3 |
| 249 | + }, |
| 250 | + "file_extension": ".py", |
| 251 | + "mimetype": "text/x-python", |
| 252 | + "name": "python", |
| 253 | + "nbconvert_exporter": "python", |
| 254 | + "pygments_lexer": "ipython3", |
| 255 | + "version": "3.11.4" |
| 256 | + } |
| 257 | + }, |
| 258 | + "nbformat": 4, |
| 259 | + "nbformat_minor": 5 |
| 260 | +} |
0 commit comments