From 31565d4d364d969abe39714709d53f9946be67b5 Mon Sep 17 00:00:00 2001 From: Jonathan Sada Date: Sun, 11 May 2025 00:01:46 +0200 Subject: [PATCH] Solved lab --- lab-python-error-handling.ipynb | 648 +++++++++++++++++++++++++++++++- 1 file changed, 644 insertions(+), 4 deletions(-) diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index 3e50ef8..77dadd9 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -39,20 +39,660 @@ "\n" ] }, + { + "cell_type": "code", + "execution_count": 30, + "id": "ba1d0b8a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: Parameters a and b must be int\n", + "False\n", + "Exception: Parameters a and b must be int\n", + "False\n", + "2\n", + "2\n", + "1\n" + ] + } + ], + "source": [ + "def greater(a, b):\n", + " result = False\n", + " try:\n", + " if not isinstance(a, int) or not isinstance(b, int):\n", + " raise TypeError(\"Parameters a and b must be int\")\n", + " except TypeError as e:\n", + " print(f\"Exception: {e}\")\n", + " except Exception as e:\n", + " print(f\"Unknown Exception: {e}\")\n", + " else:\n", + " if a > b: # A is bigger than B\n", + " result = a\n", + " elif a < b: # B is bigger than A\n", + " result = b\n", + " else: # They are equal\n", + " result = a # As there is not defined how to act in this situation I return A (since is the same than B)\n", + " finally:\n", + " return result\n", + "\n", + "print(greater(\"a\", None)) # False (Exception: Parameters a and b must be int)\n", + "print(greater(1, \"\")) # False (Exception: Parameters a and b must be int)\n", + "print(greater(1,2)) # 2\n", + "print(greater(2,1)) # 2\n", + "print(greater(1,1)) # 1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3f7c5c70", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: elements must be a list or a tuple\n", + "False\n", + "Exception: elements can't be empty\n", + "False\n", + "Exception: values in elements must be int\n", + "False\n", + "4\n", + "8\n" + ] + } + ], + "source": [ + "def greatest(elements):\n", + " greatest_num = False\n", + " try:\n", + " if not isinstance(elements, (list, tuple)):\n", + " raise TypeError(\"elements must be a list or a tuple\")\n", + " if not elements:\n", + " raise ValueError(\"elements can't be empty\") \n", + " for e in elements:\n", + " if not isinstance(e, int):\n", + " raise ValueError(\"values in elements must be int\") \n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " else:\n", + " for element in elements:\n", + " if greatest_num == False or greatest_num < element:\n", + " greatest_num = element\n", + " finally:\n", + " return greatest_num\n", + "\n", + "print(greatest({1, 2, 3, 4})) # False (Exception: elements must be a list)\n", + "print(greatest([])) # False (Exception: elements can't be empty)\n", + "print(greatest([1, \"2\", 3, 4])) # False (Exception: values in elements must be int)\n", + "print(greatest([1, 2, 3, 4])) # 4\n", + "print(greatest((5, 6, 7, 8))) # 8" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "33ac7979", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: lst must be a list or a tuple\n", + "False\n", + "Exception: lst must contain at least two integers\n", + "False\n", + "Exception: lst must contain at least two integers\n", + "False\n", + "Exception: values in lst must be int\n", + "False\n", + "3\n", + "26\n" + ] + } + ], + "source": [ + "def sum_all(lst):\n", + " result = False\n", + " try:\n", + " if not isinstance(lst, (list, tuple)):\n", + " raise TypeError(\"lst must be a list or a tuple\")\n", + " if len(lst) < 2:\n", + " raise ValueError(\"lst must contain at least two integers\") \n", + " for e in lst:\n", + " if not isinstance(e, int):\n", + " raise ValueError(\"values in lst must be int\") \n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " else:\n", + " result = 0\n", + " for num in lst:\n", + " result += num\n", + " finally:\n", + " return result \n", + "\n", + "print(sum_all({1, 2, 3, 4})) # False (Exception: lst must be a list)\n", + "print(sum_all([])) # False (Exception: lst must contain at least two integers)\n", + "print(sum_all([2])) # False (Exception: lst must contain at least two integers)\n", + "print(sum_all([1, \"2\"])) # False (Exception: values in lst must be int)\n", + "print(sum_all([1, 2])) # 2\n", + "print(sum_all((5, 6, 7, 8))) # 26" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "32940855", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: lst must be a list or a tuple\n", + "False\n", + "False\n", + "False\n", + "False\n", + "2\n", + "1680\n" + ] + } + ], + "source": [ + "def mult_all(lst):\n", + " result = False\n", + " try:\n", + " if not isinstance(lst, (list, tuple)):\n", + " raise TypeError(\"lst must be a list or a tuple\")\n", + " if len(lst) < 2:\n", + " raise ValueError(\"lst must contain at least two integers\") \n", + " for e in lst:\n", + " if not isinstance(e, int):\n", + " raise ValueError(\"values in lst must be int\") \n", + " except TypeError as e:\n", + " print(f\"Exception: {e}\")\n", + " else:\n", + " result = 1\n", + " for num in lst:\n", + " result *= num\n", + " finally:\n", + " return result \n", + "\n", + "print(mult_all({1, 2, 3, 4})) # False (Exception: lst must be a list)\n", + "print(mult_all([])) # False (Exception: lst must contain at least two integers)\n", + "print(mult_all([2])) # False (Exception: lst must contain at least two integers)\n", + "print(mult_all([1, \"2\"])) # False (Exception: values in lst must be int)\n", + "print(mult_all([1, 2])) # 2\n", + "print(mult_all((5, 6, 7, 8))) # 1680" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "2f04e56d", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: arr must be a list or a tuple\n", + "False\n", + "Exception: arr must contain at least two integers\n", + "False\n", + "Exception: arr must contain at least two integers\n", + "False\n", + "Exception: values in arr must be int\n", + "False\n", + "Exception: oper must be '+' or '*'\n", + "False\n", + "2\n", + "1680\n" + ] + } + ], + "source": [ + "def oper_all(arr, oper = \"*\"):\n", + " result = False\n", + " try:\n", + " if not oper in [\"+\", \"*\"]:\n", + " raise ValueError(\"oper must be '+' or '*'\") \n", + " # Next exceptions are not really needed because sum_all and mult_all already manage them but I wanted to customize the message\n", + " if not isinstance(arr, (list, tuple)):\n", + " raise TypeError(\"arr must be a list or a tuple\")\n", + " if len(arr) < 2:\n", + " raise ValueError(\"arr must contain at least two integers\") \n", + " for e in arr:\n", + " if not isinstance(e, int):\n", + " raise ValueError(\"values in arr must be int\") \n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " else:\n", + " if oper==\"*\":\n", + " result = mult_all(arr)\n", + " elif oper==\"+\":\n", + " result = sum_all(arr)\n", + " finally:\n", + " return result \n", + "\n", + "print(oper_all({1, 2, 3, 4})) # False (Exception: arr must be a list)\n", + "print(oper_all([])) # False (Exception: arr must contain at least two integers)\n", + "print(oper_all([2])) # False (Exception: arr must contain at least two integers)\n", + "print(oper_all([1, \"2\"])) # False (Exception: values in arr must be int)\n", + "print(oper_all([1, 2, 3, 4], oper=\"-\")) # False (Exception: oper must be '+' or '*')\n", + "print(oper_all([1, 2])) # 2\n", + "print(oper_all((5, 6, 7, 8))) # 1680" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f326c79", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: n must be an integer\n", + "False\n", + "Exception: n must be an integer\n", + "False\n", + "Exception: n can't be negative\n", + "False\n", + "720\n" + ] + } + ], + "source": [ + "def factorial(n):\n", + " try:\n", + " if not isinstance(n, int):\n", + " raise ValueError(\"n must be an integer\") \n", + " if n < 0:\n", + " raise ValueError(\"n can't be negative\") \n", + " \n", + " result = n\n", + " while n > 1:\n", + " n -= 1\n", + " result *= n\n", + " return result\n", + "\n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " return False\n", + "\n", + "print(factorial(\"\")) # False (Exception: n must be an integer)\n", + "print(factorial(None)) # False (Exception: n must be an integer)\n", + "print(factorial(-1)) # False (Exception: n can't be negative)\n", + "print(factorial(6)) # 720" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "bd821d0f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: lst_un must be a list or a tuple\n", + "False\n", + "Exception: lst_un can't be empty\n", + "False\n", + "[1]\n", + "[1, 2, 3, 4]\n" + ] + } + ], + "source": [ + "def unique(lst_un):\n", + " try:\n", + " if not isinstance(lst_un, (list, tuple)):\n", + " raise TypeError(\"lst_un must be a list or a tuple\")\n", + "\n", + " if not lst_un:\n", + " raise ValueError(\"lst_un can't be empty\")\n", + " \n", + " unique = []\n", + " for item in lst_un:\n", + " if not item in unique:\n", + " unique.append(item)\n", + " return unique\n", + "\n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " return False\n", + "\n", + "print(unique(None)) # False (Exception: lst_un must be a list or a tuple)\n", + "print(unique([])) # False (Exception: lst_un can't be empty)\n", + "print(unique((1,))) # 1 \n", + "print(unique([1,2,2,3,3,4,])) # 1 " + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "36fbca79", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: arr must be a list or a tuple\n", + "False\n", + "Exception: arr can't be empty\n", + "False\n", + "Exception: values in arr must be int\n", + "False\n", + "1\n", + "2\n" + ] + } + ], + "source": [ + "def mode_counter(arr):\n", + " try:\n", + " if not isinstance(arr, (list, tuple)):\n", + " raise TypeError(\"arr must be a list or a tuple\")\n", + "\n", + " if not arr:\n", + " raise ValueError(\"arr can't be empty\")\n", + " \n", + " for e in arr:\n", + " if not isinstance(e, int):\n", + " raise ValueError(\"values in arr must be int\") \n", + "\n", + " item_count = {}\n", + " for item in arr:\n", + " if not item in item_count:\n", + " item_count[item] = 1\n", + " else:\n", + " item_count[item] += 1\n", + "\n", + " max_mode = False\n", + " for item, num in item_count.items():\n", + " if max_mode==False or item_count[max_mode] < num:\n", + " max_mode = item\n", + "\n", + " return max_mode\n", + "\n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " return False\n", + "\n", + "print(mode_counter(None)) # False (Exception: arr must be a list or a tuple)\n", + "print(mode_counter([])) # False (Exception: arr can't be empty)\n", + "print(mode_counter((1,\"1\", 1 , \"2\"))) # False (Exception: values in arr must be int)\n", + "print(mode_counter((1,))) # 1 \n", + "print(mode_counter([1,2,2,3,3,4,])) # 2" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "9a30e5cd", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: list_sd must be a list or a tuple\n", + "False\n", + "Exception: list_sd must contail at least 2 integers\n", + "False\n", + "Exception: values in list_sd must be int\n", + "False\n", + "Exception: list_sd must contail at least 2 integers\n", + "False\n", + "0.7071067811865476\n", + "1.3451854182690985\n" + ] + } + ], + "source": [ + "def st_dev(list_sd):\n", + " try:\n", + " if not isinstance(list_sd, (list, tuple)):\n", + " raise TypeError(\"list_sd must be a list or a tuple\")\n", + "\n", + " if len(list_sd) < 2 :\n", + " raise ValueError(\"list_sd must contail at least 2 integers\")\n", + " \n", + " for e in list_sd:\n", + " if not isinstance(e, int):\n", + " raise ValueError(\"values in list_sd must be int\") \n", + "\n", + " #your code here\n", + " # Step 1: Find the mean.\n", + " num_count = 0\n", + " num_sum = 0\n", + " for num in list_sd:\n", + " num_sum += num\n", + " num_count += 1\n", + " mean = num_sum / num_count\n", + "\n", + " # Step 2: Subtract the mean from each score.\n", + " lst_deviation = [(num - mean) for num in list_sd]\n", + "\n", + " # Step 3: Square each deviation.\n", + " lst_square_deviations = [num**2 for num in lst_deviation]\n", + " \n", + " # Step 4: Add the squared deviations.\n", + " sum_sq_deviation = 0\n", + " for num in lst_square_deviations:\n", + " sum_sq_deviation += num\n", + "\n", + " # Step 5: Divide the sum by the number of scores.\n", + " variance = sum_sq_deviation / (num_count-1) # Tests are looking for the \"sample standard deviation\" so I need to take 1 from the num_count\n", + "\n", + " # Step 6: Take the square root of the result from Step 5.\n", + " return variance**(1/2)\n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " return False\n", + "\n", + "print(st_dev(None)) # False (Exception: list_sd must be a list or a tuple)\n", + "print(st_dev([])) # False (Exception: list_sd must contail at least 2 integers)\n", + "print(st_dev((1,\"1\", 1 , \"2\"))) # False (Exception: values in list_sd must be int)\n", + "print(st_dev((1,))) # False (Exception: list_sd must contail at least 2 integers)\n", + "print(st_dev((1, 2))) # 0.7071067811865476\n", + "print(st_dev([1,2,2,3,3,4,5])) # 1.3451854182690985" + ] + }, { "cell_type": "code", "execution_count": null, + "id": "512a6b81", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: parameter string must be a string\n", + "False\n", + "Exception: pangram must have at least 26 letters (as the abecedary)\n", + "False\n", + "True\n" + ] + } + ], + "source": [ + "def pangram(string):\n", + " try:\n", + " if not isinstance(string, str):\n", + " raise TypeError(\"parameter string must be a string\")\n", + "\n", + " if len(string) < 26:\n", + " raise ValueError(\"pangram must have at least 26 letters (as the abecedary)\")\n", + "\n", + " letters = {}\n", + " string = string.lower()\n", + " return len(unique([char for char in string if char.isalpha()])) == 26\n", + "\n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " return False \n", + "\n", + "print(pangram(None)) # False (Exception: parameter string must be a string)\n", + "print(pangram(\"abcd\")) # False (pangram must have at least 26 letters (as the abecedary))\n", + "print(pangram(\"abcdefghijklmnopqrstuvwxyz\")) # True" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "id": "426e172e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: parameter string must be a string\n", + "False\n", + "Exception: string can't be empty\n", + "False\n", + "Exception: word separator must be , without spaces\n", + "False\n", + "bike,car,truck,wagon\n" + ] + } + ], + "source": [ + "def sort_alpha(string):\n", + " try:\n", + " if not isinstance(string, str):\n", + " raise TypeError(\"parameter string must be a string\")\n", + "\n", + " if not string:\n", + " raise ValueError(\"string can't be empty\")\n", + "\n", + " if \", \" in string or \" ,\" in string:\n", + " raise TypeError(\"word separator must be , without spaces\")\n", + "\n", + " words = []\n", + " curr_word = \"\"\n", + " for char in string:\n", + " if char != \",\":\n", + " curr_word += char\n", + " else:\n", + " words.append(curr_word)\n", + " curr_word = \"\"\n", + " words.append(curr_word)\n", + "\n", + " # Sort\n", + " words = sorted(words)\n", + "\n", + " # result\n", + " result = \"\"\n", + " for word in words:\n", + " result += word+\",\"\n", + " \n", + " return result[:-1]\n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " return False \n", + "\n", + "print(sort_alpha(None)) # False (Exception: parameter string must be a string)\n", + "print(sort_alpha(\"\")) # False (Exception: string can't be empty)\n", + "print(sort_alpha(\"car, truck , wagon\")) # False (Exception: word separator must be , without spaces)\n", + "print(sort_alpha(\"car,truck,bike,wagon\")) # bike,car,truck,wagon" + ] + }, + { + "cell_type": "code", + "execution_count": 55, "id": "cc2c441d-9dcf-4817-b097-cf6cbe440846", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Exception: password can't be empty\n", + "False\n", + "Exception: Must be at least 8 characters.\n", + "False\n", + "Exception: Must contain at least 1 upper case character. \n", + "False\n", + "Exception: Must contain at least 1 number. \n", + "False\n", + "Exception: Must contain at least 1 special character. \n", + "False\n", + "Exception: Must contain at least 1 lower case character. \n", + "False\n", + "True\n" + ] + } + ], "source": [ - "# your code goes here" + "import string\n", + "def check_pass(password):\n", + " try:\n", + " if not isinstance(password, str):\n", + " raise TypeError(\"password must be a string\")\n", + "\n", + " if not password:\n", + " raise ValueError(\"password can't be empty\")\n", + "\n", + " special_chars = string.punctuation\n", + "\n", + " count_len = 0\n", + " count_lower = 0\n", + " count_upper = 0\n", + " count_number = 0\n", + " count_special = 0\n", + " \n", + " for char in password:\n", + " count_len += 1\n", + " count_lower += 1 if char.islower() else 0\n", + " count_upper += 1 if char.isupper() else 0\n", + " count_number += 1 if char.isnumeric() else 0\n", + " count_special += 1 if char in special_chars else 0\n", + "\n", + " if count_len < 8:\n", + " raise ValueError(\"Must be at least 8 characters.\")\n", + " if count_lower < 1:\n", + " raise ValueError(\"Must contain at least 1 lower case character. \")\n", + " if count_upper < 1:\n", + " raise ValueError(\"Must contain at least 1 upper case character. \")\n", + " if count_number < 1:\n", + " raise ValueError(\"Must contain at least 1 number. \")\n", + " if count_special < 1:\n", + " raise ValueError(\"Must contain at least 1 special character. \")\n", + " \n", + " return all([count_len>=8, count_lower>=1, count_upper>=1, count_number>=1, count_special>=1])\n", + "\n", + " except Exception as e:\n", + " print(f\"Exception: {e}\")\n", + " return False \n", + "\n", + "print(check_pass(\"\")) # False (Exception: password can't be empty)\n", + "print(check_pass(\"aA4!\")) # False (Exception: Must be at least 8 characters.)\n", + "print(check_pass(\"aaaaaaaa\")) # False (Exception: Must contain at least 1 upper case character. )\n", + "print(check_pass(\"aaaaAAAA\")) # False (Exception: Must contain at least 1 number )\n", + "print(check_pass(\"abcABC123\")) # False (Exception: Must contain at least 1 special character. )\n", + "print(check_pass(\"ABAB12!$\")) # False (Exception: Must contain at least 1 lower character. )\n", + "print(check_pass(\"abAB12!$\")) # True" ] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "Python 3", "language": "python", "name": "python3" }, @@ -66,7 +706,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.11.12" } }, "nbformat": 4,