diff --git a/cours-exercices/01-data-structures-complexity-exercises.ipynb b/cours-exercices/01-data-structures-complexity-exercises.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f5be24e94fd9acd4aa4ce9470ebe0936dd27617c --- /dev/null +++ b/cours-exercices/01-data-structures-complexity-exercises.ipynb @@ -0,0 +1,269 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "82b57c5e", + "metadata": {}, + "source": [] + }, + { + "cell_type": "markdown", + "id": "e8a19c58", + "metadata": {}, + "source": [ + "# INF TC1 - Algorithmes et structures de données\n", + "\n", + "## Exercices" + ] + }, + { + "cell_type": "markdown", + "id": "2968208d", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "a4e4fad3", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Data Structures and Complexity" + ] + }, + { + "cell_type": "markdown", + "id": "a8adef9b", + "metadata": { + "slideshow": { + "slide_type": "skip" + } + }, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "827ebb43-1e5d-4756-83ba-97af3e36b6af", + "metadata": {}, + "source": [ + "_For the following question, if a complexity is needed please pick one in this list_" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b54157fc-f0d5-4689-bf2b-344a608bc5a9", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "list_complexities = [\"O(1)\", \"O(log(n))\", \"O(n)\", \"O(n^2)\", \"O(nlog(n))\", \"O(n^3)\", \"O(2^n)\", \"O(n!)\", \"O(n^n)\"]" + ] + }, + { + "cell_type": "markdown", + "id": "568202fd", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### Exercise 1: Identify the complexity" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "431fe8c1-91d1-40f3-a7a4-f4a3770a4a01", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "def nested_loop_example(arr):\n", + " n = len(arr)\n", + " for i in range(n):\n", + " for j in range(n):\n", + " print(arr[i] + arr[j])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e68b3e9a-418f-4950-9f27-18bb0fe90794", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "1a3b054c6051bc0e03a25ef29d1c373b", + "grade": false, + "grade_id": "cell-a06bfe9af33fe998", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# nested_loop_example_complexity = ?\n", + "# YOUR CODE HERE\n", + "raise NotImplementedError()" + ] + }, + { + "cell_type": "markdown", + "id": "612dc873-419b-42c5-be36-0accd03ffa79", + "metadata": {}, + "source": [ + "### Exercise 2: Identify the complexity" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "76102853-e1f3-4717-8a59-1091195a19eb", + "metadata": {}, + "outputs": [], + "source": [ + "def fibonacci_recursive(n):\n", + " if n <= 1:\n", + " return n\n", + " return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dead6a52-7996-4eae-9d2a-f75d5d26bbb7", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "1eadb247ef5c5224aa6800e2d7846174", + "grade": false, + "grade_id": "cell-34e130eb0c6b7e82", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# fibonacci_recursive_complexity = ?\n", + "# YOUR CODE HERE\n", + "raise NotImplementedError()" + ] + }, + { + "cell_type": "markdown", + "id": "aa4a6ce7-e542-4b23-8a10-ca0bf93de041", + "metadata": {}, + "source": [ + "### Exercise 3: Identify the complexity" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "70af3e43-8053-49c9-ba58-346a3e915bdb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "def binary_search(arr, target):\n", + " low, high = 0, len(arr) - 1\n", + " while low <= high:\n", + " mid = (low + high) // 2\n", + " if arr[mid] == target:\n", + " return mid\n", + " elif arr[mid] < target:\n", + " low = mid + 1\n", + " else:\n", + " high = mid - 1\n", + " return -1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9c22866c-b4fc-4228-b0ab-5882d964f5f6", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "5f3471162e0167bb6022ece5eed0a4f7", + "grade": false, + "grade_id": "cell-ea8595a5923fbb0e", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# binary_searche_complexity = ?\n", + "# YOUR CODE HERE\n", + "raise NotImplementedError()" + ] + }, + { + "cell_type": "markdown", + "id": "87b4921b-ef55-4083-b4f1-a3ca5bb7b011", + "metadata": {}, + "source": [ + "### Additional checks (do not change)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6e8f2878-ce5f-4cd8-a5a5-7bce8f655ab8", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "assert nested_loop_example_complexity in list_complexities\n", + "assert fibonacci_recursive_complexity in list_complexities\n", + "assert binary_searche_complexity in list_complexities" + ] + } + ], + "metadata": { + "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.10.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/cours-exercices/02-recursion-exercises.ipynb b/cours-exercices/02-recursion-exercises.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..393150afc1798f27a31e204c9af0a8efccf6825b --- /dev/null +++ b/cours-exercices/02-recursion-exercises.ipynb @@ -0,0 +1,1086 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "552c2490", + "metadata": {}, + "source": [] + }, + { + "cell_type": "markdown", + "id": "4aaf8acc", + "metadata": {}, + "source": [ + "# INF TC1 - Algorithmes et structures de données\n", + "\n", + "## Exercices" + ] + }, + { + "cell_type": "markdown", + "id": "6a4b8ca4", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "a4e4fad3", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Recursion" + ] + }, + { + "cell_type": "markdown", + "id": "a8adef9b", + "metadata": { + "slideshow": { + "slide_type": "skip" + } + }, + "source": [ + "---" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0dfe1da3-b50b-49c0-aaff-483616e13863", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "list_complexities = [\"O(1)\", \"O(log(n))\", \"O(n)\", \"O(n^2)\", \"O(nlog(n))\", \"O(n^3)\", \"O(2^n)\", \"O(n!)\", \"O(n^n)\"]" + ] + }, + { + "cell_type": "markdown", + "id": "568202fd", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### Exercise 0: Find the maximum value in a list (iterative)\n", + "\n", + "Write a function `find_maximum_iterative` that takes a list of numbers as input and returns the maximum value in the list. For this question, you are not allowed to use built-in functions like `max()`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "431fe8c1-91d1-40f3-a7a4-f4a3770a4a01", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "8b23d599da9ca2bdba48b9bcdd6e1165", + "grade": false, + "grade_id": "find_maximum_iterative", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def find_maximum_iterative(L):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f6baae3c-3660-4add-ab4b-48016cba3030", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "find_maximum_iterative([1, 3, 5, 7, 9])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e68b3e9a-418f-4950-9f27-18bb0fe90794", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "9cb3441fa27dd28ce74e368375de8080", + "grade": true, + "grade_id": "correct_find_maximum_iterative", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert find_maximum_iterative([1, 3, 5, 7, 9]) == 9\n", + "assert find_maximum_iterative([-1, -5, -3]) == -1\n", + "assert find_maximum_iterative([42]) == 42\n", + "assert find_maximum_iterative([4, 8, 8, 2, 7]) == 8\n", + "assert find_maximum_iterative([-10, -5, -8, -2, -7]) == -2" + ] + }, + { + "cell_type": "markdown", + "id": "612dc873-419b-42c5-be36-0accd03ffa79", + "metadata": {}, + "source": [ + "### Exercise 1: Find the maximum value in a list (recursive)\n", + "\n", + "Write a recursive version of the previous function; you may use the `max()` function for the recursive call." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "07668fd8", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "fcd4348ffdf05fa800f15e7dba033d8e", + "grade": false, + "grade_id": "find_maximum_recursive", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def find_maximum_recursive(L):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f9784710-4b2b-434c-bc47-da46fa410749", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "find_maximum_recursive([1, 3, 5, 7, 9])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9b0161f8-0539-4e5e-921c-1886e61c0783", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "1aae7ba6a868f7afd015deedcdf48aa4", + "grade": true, + "grade_id": "correct_find_maximum_recursive", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert find_maximum_iterative([-10, -5, -8, -2, -7]) == find_maximum_recursive([-10, -5, -8, -2, -7])" + ] + }, + { + "cell_type": "markdown", + "id": "005efd41-baa1-4505-b80e-3644d61ea094", + "metadata": {}, + "source": [ + "### Exercise 2: Sum of digits" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "de424156-0b9b-41d0-8e38-ce335f35cec0", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "3872f4f922847e273bc5a45cd425c458", + "grade": false, + "grade_id": "sum_of_digits", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def sum_of_digits(n):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cec0caca-cb2c-4e4d-b004-27b3cf2ff611", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "sum_of_digits(10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bf276ca2-48ed-4e87-80f2-776f54b7062b", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "feb0a5b734f6734920bfec23da86992b", + "grade": true, + "grade_id": "correct_sum_of_digits", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert sum_of_digits(10) == sum_of_digits(100000)\n", + "assert sum_of_digits(0) == 0\n", + "assert sum_of_digits(123) == 6" + ] + }, + { + "cell_type": "markdown", + "id": "e2de630a-f9bd-4d45-959b-430e34cc9044", + "metadata": { + "tags": [] + }, + "source": [ + "### Exercise 3: Calculate the power" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "abca03a0-7bcd-4ee6-b109-ff2f2da52bb6", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "c8c385784b4dd53e96c693511e7a2e80", + "grade": false, + "grade_id": "power", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def power(base, exponent):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "abddd3b1-f75f-4cb6-a09e-54eed489c5b0", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "power(2, 10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8a6605fe-4f6f-45de-84a3-7601e2e2e6f6", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "1deb1e7cdc63de1900c5375bf6debf2a", + "grade": true, + "grade_id": "correct_power", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert power(2, 10) == 1024\n", + "assert power(2, 0) == 1\n", + "assert power(5, 3) == 125" + ] + }, + { + "cell_type": "markdown", + "id": "715100d3-fc21-49b9-a66d-b5243b4a279d", + "metadata": { + "tags": [] + }, + "source": [ + "### Exercise 4: Reverse a string" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ddc9826a-0863-4777-a08d-81b66652b5a5", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "762d91a747e5399677a26e44c5d8a041", + "grade": false, + "grade_id": "reverse_string", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def reverse_string(s):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "13acad7e-d03c-4ea6-ad86-baf02e0910eb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "reverse_string(\"Romain\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "453c8e04-6cd9-4581-a206-dd479b6115cd", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "d42cbfb82df47fb4eb82e1530fa8f3cb", + "grade": true, + "grade_id": "correct_reverse_string", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert reverse_string(\"\") == \"\"\n", + "assert reverse_string(\"AA\") == \"AA\"\n", + "assert reverse_string(\"ABC\") == \"CBA\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "159b6d78-03ae-4cf8-8545-e822b7160b32", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "def iterative_reverse_string(s):\n", + " reversed_str = \"\"\n", + " for char in s:\n", + " reversed_str = char + reversed_str\n", + " return reversed_str" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "43e10b0c", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "5ab8f3c9-ddee-45ab-a013-fdd67d9853e0", + "metadata": {}, + "source": [ + "### Example 5: convert an interative suite into a recursive tail function" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "219add7f", + "metadata": { + "slideshow": { + "slide_type": "subslide" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def sequence(n):\n", + " u = 1\n", + " while n > 0:\n", + " u = 2 * u + 1\n", + " n -= 1\n", + " return u" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0787df24-8234-4286-b910-5f9e456dd279", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "print(\"The result is {}\".format(sequence(3)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9c17cf1b-6d05-4589-af2b-c05cfcc33202", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "2137e4ccdef7bccaa7b7ed6b52f305a8", + "grade": false, + "grade_id": "sequence_recursive_tail", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def sequence_recursive_tail(n):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "43507c43-de61-414d-b389-c0a771ad9e0c", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "print(\"The result is still {}\".format(sequence_recursive_tail(3)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dd923b7c-0cab-4678-8dc3-aad2ab9b25f9", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "c465dc72b44f305c781da5cf50e4c934", + "grade": true, + "grade_id": "correct_sequence_recursive_non_tail", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "slideshow": { + "slide_type": "slide" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert sequence_recursive_tail(3) == 15" + ] + }, + { + "cell_type": "markdown", + "id": "3c28b36a", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "source": [ + "### Example 6: check if a word is a palindrom\n", + "\n", + "Check if a word can be read backwards." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "51bb3d08", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "a11e9594f7e72af63464586312e41230", + "grade": false, + "grade_id": "annagram_rec", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def palindrom_rec(word):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0c279628-9b96-4687-8e20-a954ab646e0f", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "palindrom_rec(\"laval\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cf6fa61a-7c6f-4a32-96c2-b9fd50deacc6", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "ef3b3eadc729e907ea2d4da9b32fed0c", + "grade": true, + "grade_id": "correct_annagram_rec", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert palindrom_rec(\"\")\n", + "assert palindrom_rec(\"AA\")\n", + "assert not palindrom_rec(\"ABC\")\n", + "assert palindrom_rec(\"ABA\")\n", + "assert palindrom_rec(\"LAVAL\")" + ] + }, + { + "cell_type": "markdown", + "id": "798c2875-7940-488a-8458-ad08f6a71c70", + "metadata": {}, + "source": [ + "### Example 7: Calculate GCD\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "48c65c83-be0c-41c4-8c04-1d29ac4415cb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "def iterative_gcd(a, b):\n", + " while b:\n", + " a, b = b, a % b\n", + " return a" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bf6e1a76", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "45353cb0fdd92b57e6f6f1739ed430b3", + "grade": false, + "grade_id": "recursive_gcd", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def recursive_gcd(a, b):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4f1feace", + "metadata": {}, + "outputs": [], + "source": [ + "recursive_gcd(10, 2)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e6ff1765-ff4b-49a5-80d3-684d2627e961", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "ed3ae90c2a4be5ff93a5d68b688f0f96", + "grade": true, + "grade_id": "correct_recursive_gcd", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert iterative_gcd(10, 2) == recursive_gcd(10, 2)" + ] + }, + { + "cell_type": "markdown", + "id": "d8b05edf-9536-4fc1-bfcc-ddbbeee426fc", + "metadata": {}, + "source": [ + "### Example 8: Check if a list is sorted" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1661dfb5-88f2-411f-8fe2-63bbaa29ce72", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "9fcedc9d6262baf07013d0b6f4e8175d", + "grade": false, + "grade_id": "calculate_average_recursive", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def is_sorted(lst):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0c5c72c6-3237-4f98-ab96-50a1838b833f", + "metadata": {}, + "outputs": [], + "source": [ + "is_sorted([1, 2, 3, 4, 5])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9f18b6b7-d980-4a72-a2a8-3aa201003d21", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "9cdabb05d7be086c1b769672a158fdc6", + "grade": true, + "grade_id": "correct_calculate_average_recursive", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert is_sorted([2, 3])" + ] + }, + { + "cell_type": "markdown", + "id": "79eef392-1d3d-46c0-aeee-ac805686e6f1", + "metadata": {}, + "source": [ + "### Example 9: Check for prime number" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ac374a08-11c9-47e6-ba11-419549911266", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "58fec5e697f40d4e1934bdce3ae87647", + "grade": false, + "grade_id": "is_prime_recursive", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def is_prime_recursive(n, divisor=2):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "996fc91f", + "metadata": {}, + "outputs": [], + "source": [ + "is_prime_recursive(3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5be1051c-3b60-4810-b855-6f8575ad6380", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "f571ff3e3a5bc53ffbc828b255bfb6cb", + "grade": true, + "grade_id": "correct_is_prime_recursive", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert is_prime_recursive(3) " + ] + }, + { + "cell_type": "markdown", + "id": "5423682d-c31f-4a8d-9a0f-6812de7b1ae3", + "metadata": {}, + "source": [ + "### Example 10: Count occurrences of a given element in a list" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cfeb0ad0-ed82-499e-9af3-64923291a0e7", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "01c4970fffe483944b93049b5d8404a0", + "grade": false, + "grade_id": "count_occurrences", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def count_occurrences(arr, target, index=0):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "49daec07-00b3-412e-ad44-5bafadbd9f36", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "count_occurrences([1, 2, 3, 4, 2, 2, 5, 6, 2], 2)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "14a2eb85-1126-4506-93bb-4bf624d046b6", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "5df4afd6ed2f7dfd102b8c21f8ced2e7", + "grade": true, + "grade_id": "correct_count_occurrences", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert count_occurrences([1, 2, 3, 4, 2, 2, 5, 6, 2], 2) == 4" + ] + }, + { + "cell_type": "markdown", + "id": "bb1784f5-2426-4661-aa13-dba96743ceb5", + "metadata": {}, + "source": [ + "# Bonus" + ] + }, + { + "cell_type": "markdown", + "id": "7fdcd705-dc0b-4614-8e27-9ba62f8fe442", + "metadata": {}, + "source": [ + "### Exercise: Find the maximum value in a list (iterative)\n", + "\n", + "Check that an empty lists raises a `ValueError` exception with a `\"The list is empty.\"` message." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f9334f32-f760-46c0-a649-c82f267aba5b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "try:\n", + " result = find_maximum_iterative([])\n", + " assert False, \"Exception not raised\"\n", + "except ValueError as e:\n", + " assert str(e) == \"The list is empty.\", f\"Expected error message: 'The list is empty.' but got '{str(e)}'\"" + ] + }, + { + "cell_type": "markdown", + "id": "c121315a-4aaa-4e04-912f-73f56555be56", + "metadata": {}, + "source": [ + "### Exercise: Find the maximum value in a list (recursive)\n", + "\n", + "Witout using the built-in `max` function" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "153e3f05-7598-4920-bc8d-8943cb75e5a8", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# checks if a function uses another function, eg \"max\"\n", + "import inspect\n", + "\n", + "def calls_builtin_max(func):\n", + " source_code = inspect.getsource(func)\n", + " return 'max(' in source_code\n", + "\n", + "def my_function(lst):\n", + " return max(lst)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "775b7e32-a5ae-431b-9987-fcd3671fd022", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "def find_maximum_recursive_no_max_func(L): \n", + " if not L:\n", + " raise ValueError(\"The list is empty.\")\n", + " \n", + " if len(L) == 1:\n", + " return L[0]\n", + " \n", + " rest_max = find_maximum_recursive(L[1:])\n", + " return L[0] if L[0] > rest_max else rest_max" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f76ed657-3288-4b36-9175-21168d2eb761", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "assert not calls_builtin_max(find_maximum_recursive_no_max_func)" + ] + }, + { + "cell_type": "markdown", + "id": "bbe7023a-aabd-489d-bae6-3b71566e22ef", + "metadata": {}, + "source": [ + "# Additional tests (do not change)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1c73ad0e-ddc9-483d-85a1-f2a65d04f30b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "assert calls_builtin_max(my_function)\n", + "assert not calls_builtin_max(find_maximum_iterative)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8ce960f5-08da-449e-9e6f-dae215bc1b6a", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# generates more examples for a given function\n", + "def gen_examples(fnct, n=10):\n", + " return [fnct(i) for i in range(0, n)]" + ] + } + ], + "metadata": { + "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.10.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/cours-exercices/03-lists-search-sort-exercises.ipynb b/cours-exercices/03-lists-search-sort-exercises.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e620c33bb1454074ae859ab36d4fe22db62c7cf1 --- /dev/null +++ b/cours-exercices/03-lists-search-sort-exercises.ipynb @@ -0,0 +1,667 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "8c52d3d4", + "metadata": {}, + "source": [] + }, + { + "cell_type": "markdown", + "id": "74aa4459", + "metadata": {}, + "source": [ + "# INF TC1 - Algorithmes et structures de données\n", + "\n", + "## Exercices" + ] + }, + { + "cell_type": "markdown", + "id": "d9a28297", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "e58599e3-9ab7-4d43-bb22-aeccade424ce", + "metadata": {}, + "source": [ + "# Lists, search, sort" + ] + }, + { + "cell_type": "markdown", + "id": "691b3c38-0e83-4bb2-ac90-ef76d2dd9a7a", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1095285f-26e2-43ce-a1c5-9358c5256a0b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "list_complexities = [\"O(1)\", \"O(log(n))\", \"O(n)\", \"O(n^2)\", \"O(nlog(n))\", \"O(n^3)\", \"O(2^n)\", \"O(n!)\", \"O(n^n)\"]" + ] + }, + { + "cell_type": "markdown", + "id": "11a124a7-1279-469a-b091-2833d3fd1a0f", + "metadata": {}, + "source": [ + "## Exercise 0: Search the index first occurence of a target value\n", + "\n", + "_Write a Python function `search_list(L, v)` that takes a list `L` and a target element `v` as input. The function should return the index of the first occurrence of the target element in the list `L`._" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "665c7b64-428d-468a-860b-65d0d12e98e1", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "def search_list(L, target):\n", + " for n, i in enumerate(L):\n", + " if i == target:\n", + " return n\n", + " return -1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d776ca94-1ed2-4443-91e2-a1591a1690b8", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "search_list([1, 2, 2], 2)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e7b5950c-a6f0-4795-995b-903d717f35c9", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "assert search_list([1, 2, 3, 4, 5], 3) == 2\n", + "assert search_list([1, 2, 3, 4, 5], 6) == -1\n", + "assert search_list([1, 2, 3, 4, 5], 6) == -1\n", + "assert search_list([], 42) == -1\n", + "assert search_list([7, 2, 3, 4, 5], 7) == 0\n", + "assert search_list([1, 2, 3, 4, 5, 6], 7) == -1" + ] + }, + { + "cell_type": "markdown", + "id": "9d813205-b709-42ab-b414-6f3fc947022a", + "metadata": {}, + "source": [ + "## Exercise 1: Search in a list with an odd index\n", + "\n", + "_Write a Python function `search_list(L, v)` that takes a list `L` and a target element `v` as input. The function should return the index of the first occurrence of the target element in the list `L`._" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f3b233ec-7077-479d-9c04-f1a4c35f3111", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "2791444cbfd4f0f74f1ce7f2a330ecec", + "grade": false, + "grade_id": "search_list", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def search_list(L, target):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f280eeea-4812-4a30-80b5-3fe1cafa9283", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "search_list([1, 2, 2], 3)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "423d2637-8bd6-4e8f-95ff-2765dae5bce7", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "6054e435b1f5635d18f61f94bfb05e62", + "grade": true, + "grade_id": "correct_correct_search_list", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert search_list([1, 2, 3, 4, 5], 3) == 2\n", + "assert search_list([1, 2, 3, 4, 5], 6) == -1\n", + "assert search_list([1, 2, 3, 4, 5, 6], 6) == -1\n", + "assert search_list([], 42) == -1\n", + "assert search_list([7, 2, 3, 4, 5, 7], 7) == 0\n", + "assert search_list([1, 2, 3, 4, 5, 6], 6) == -1" + ] + }, + { + "cell_type": "markdown", + "id": "6d8dc6cd-aad0-42a9-b768-6a1a5289e354", + "metadata": {}, + "source": [ + "## Exercise 2: Sort a list of tuples\n", + "\n", + "_Given a list of lists of length N, sort by the N-th element of the list._" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8271ff47-efb4-48a0-ac4c-bba6ede7e578", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "18319fc9882c760de9d2f2dde25e2c76", + "grade": false, + "grade_id": "sort_list_of_lists_by_nth_element", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def sort_list_of_lists_by_nth_element(list_of_lists, N):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4577bd24-9e50-4172-8246-d1bccfa21618", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "list_of_lists = [[3, 5, 1], [1, 2, 9], [7, 4, 6], [2, 8, 3]]\n", + "sorted_list = sort_list_of_lists_by_nth_element(list_of_lists, 2)\n", + "print(sorted_list)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ed3cdeed-07fa-461f-b7ae-210e1605ca76", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "135ef51ad6ac5ce059a50fccc46a99e4", + "grade": true, + "grade_id": "correct_sort_list_of_lists_by_nth_element", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "list1 = [[3, 5, 1], [1, 2, 9], [7, 4, 6], [2, 8, 3]]\n", + "sorted_list1 = sort_list_of_lists_by_nth_element(list1, 2)\n", + "assert sorted_list1 == [[3, 5, 1], [2, 8, 3], [7, 4, 6], [1, 2, 9]], \"Test Case 1 Failed\"\n", + "\n", + "list2 = [[9, 5, 7], [3, 6, 1], [0, 2, 4], [8, 1, 5]]\n", + "sorted_list2 = sort_list_of_lists_by_nth_element(list2, 0)\n", + "assert sorted_list2 == [[0, 2, 4], [3, 6, 1], [8, 1, 5], [9, 5, 7]], \"Test Case 2 Failed\"\n", + "\n", + "list3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n", + "sorted_list3 = sort_list_of_lists_by_nth_element(list3, 1)\n", + "assert sorted_list3 == [[1, 2, 3], [4, 5, 6], [7, 8, 9]], \"Test Case 3 Failed\"\n" + ] + }, + { + "cell_type": "markdown", + "id": "0bbda1ba-a5e7-4a1d-a742-84d0215b1e24", + "metadata": {}, + "source": [ + "## Exercise 3: Access a list element\n", + "\n", + "_Given an input list `L`, and `index` value, access a given `key` and return the value._" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2d6a6f11-d24b-4f0e-a7d2-298243e35c4d", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "df3e8c605c7e96af2267865e04990e5a", + "grade": false, + "grade_id": "cell-1ab0b636df63501a", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def access_dict_element(L, index, key):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ea0883dc-d08c-40ea-9e0b-4f0a3abc517f", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "example_list = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]\n", + "result = access_dict_element(example_list, 0, 'name')\n", + "print(result) " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "88ae441e-58b1-4d6c-a639-530919658d03", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "efa0cb4d52536298b425a5e9d5154374", + "grade": true, + "grade_id": "correct_access_dict_element", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "example_list = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]\n", + "assert access_dict_element(example_list, 0, 'name') == 'Alice'\n", + "assert access_dict_element(example_list, 1, 'city') is None\n", + "assert access_dict_element(example_list, 2, 'name') is None\n", + "assert access_dict_element(example_list, 0, 'city') is None" + ] + }, + { + "cell_type": "markdown", + "id": "98405b12-ad61-4007-8c9f-6955d238df41", + "metadata": { + "tags": [] + }, + "source": [ + "## Exercise 4: Remove Elements from a List\n", + "\n", + "_Write a Python function `remove_elements(L, condition)` that takes a list `L` and a function `condition` as input._" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e079e47b-2f9e-42d1-a78b-56c92ad84d63", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "def is_odd(x):\n", + " return x % 2 != 0" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "536734bd-d4cc-4f83-8042-3c0e774c4034", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "46e9b2d0caa1061f9d00cf2859441701", + "grade": false, + "grade_id": "remove_elements", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def remove_elements(lst, condition):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a65bb6f1-b7c7-4156-ba8b-9b72a25616f3", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", + "remove_elements(my_list, is_odd)\n", + "print(my_list) # Should print [2, 4, 6, 8]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "254155dc-b271-4881-ac65-5a11d13990ea", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "d60a1be7322087e5612fb15fc5677539", + "grade": true, + "grade_id": "correct_remove_elements", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "test_list_1 = [12, 5, 18, 9, 25, 3, 15]\n", + "remove_elements(test_list_1, lambda x: x > 10)\n", + "assert test_list_1 == [5, 9, 3], \"Remove greater than 30\"\n", + "\n", + "test_list_2 = [-3, 7, -9, 2, 0, -1, 8]\n", + "remove_elements(test_list_2, lambda x: x < 0)\n", + "assert test_list_2 == [7, 2, 0, 8], \"Remove negative elements\"\n", + "\n", + "def custom_condition(x):\n", + " return x % 3 == 0\n", + "test_list_3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", + "remove_elements(test_list_3, custom_condition)\n", + "assert test_list_3 == [1, 2, 4, 5, 7, 8]\n", + "\n", + "test_list_4 = [42, 99, 101]\n", + "remove_elements(test_list_4, lambda x: True)\n", + "assert test_list_4 == [], \"Remove all elements\"\n", + "\n", + "test_list_5 = [10, 20, 30, 40]\n", + "remove_elements(test_list_5, lambda x: False)\n", + "assert test_list_5 == [10, 20, 30, 40], \"No element to remove\"" + ] + }, + { + "cell_type": "markdown", + "id": "d75dba4b-ac22-4f2c-9a6c-cf333b1ec5e8", + "metadata": {}, + "source": [ + "## Exercise 5: Sort a dictionnary by values\n", + "\n", + "List a dictionnary (not a list!) by value." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "556be9d8-b8c3-4f1d-bcb1-8f099968af9d", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "6bfb51c12c41947733534307eb1cf5c4", + "grade": false, + "grade_id": "sort_dict_by_values", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def sort_dict_by_values(input_dict):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()\n", + " return sorted_dict" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3c32c4ee-56f5-46b5-a8b6-b740e6d5fef5", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "test_dict3 = {'c': 3, 'b': 2, 'a': 1}\n", + "sorted_dict3 = sort_dict_by_values(test_dict3)\n", + "assert sorted_dict3 == {'a': 1, 'b': 2, 'c': 3}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "532e5225-a2d8-4c10-a036-1efde9acc5fd", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "8a4001090e87ce0c5d773621ed0a3ea9", + "grade": true, + "grade_id": "correct_sort_dict_by_values", + "locked": true, + "points": 0, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "test_dict = {'banana': 3, 'apple': 1, 'cherry': 2}\n", + "sorted_dict = sort_dict_by_values(test_dict)\n", + "assert sorted_dict == {'apple': 1, 'cherry': 2, 'banana': 3}\n", + "\n", + "test_dict2 = {'zebra': 42, 'lion': 7, 'elephant': 15, 'giraffe': 23}\n", + "sorted_dict2 = sort_dict_by_values(test_dict2)\n", + "assert sorted_dict2 == {'lion': 7, 'elephant': 15, 'giraffe': 23, 'zebra': 42}\n", + "\n", + "test_dict3 = {'one': 3, 'two': 3, 'three': 3, 'four': 3}\n", + "sorted_dict3 = sort_dict_by_values(test_dict3)\n", + "assert sorted_dict3 == {'one': 3, 'two': 3, 'three': 3, 'four': 3}" + ] + }, + { + "cell_type": "markdown", + "id": "fef2ad7f-55ef-43f2-991d-5067bb085eb6", + "metadata": {}, + "source": [ + "## Exercise 6: insertion sort\n", + "\n", + "Implement the `insertion sort` that operates as follows:\n", + "\n", + "- Start with an unsorted list.\n", + "- Iterate through each element in the list.\n", + "- For each element, compare it with the elements to its left in the list.\n", + "- Move elements to the right until you find the correct position for the current element.\n", + "- Insert the current element into its proper place in the sorted portion of the list.\n", + "- Repeat this process for all elements, gradually building a sorted list from left to right." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "51a86852-f8e2-4c05-8053-13fdf2a4832b", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "84421b7199764b6fe3485117b23fb0a1", + "grade": false, + "grade_id": "insertion_sort", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def insertion_sort(arr):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fbfa74f1-4675-452f-897b-21b0c7025f81", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "print(insertion_sort([2, 1, 3, 4, 5]))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "266e89e0-4b59-441f-bb67-69ad4e35e2a9", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "dc6fc6f16aa2c62a5e1e39382106b0bf", + "grade": true, + "grade_id": "correct_insertion_sort", + "locked": true, + "points": 1, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# Test case 2: Already sorted list\n", + "arr = [1, 2, 3, 4, 5]\n", + "assert insertion_sort(arr) == arr\n", + "\n", + "# Test case 3: Reverse sorted list\n", + "arr = [5, 4, 3, 2, 1]\n", + "assert insertion_sort(arr) == [1, 2, 3, 4, 5]\n", + "\n", + "# Test case 4: Random order list\n", + "arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]\n", + "assert insertion_sort(arr) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]" + ] + }, + { + "cell_type": "markdown", + "id": "ab78dd44-bb6a-451d-8642-223639d31bf9", + "metadata": {}, + "source": [ + "## Bonus\n", + "\n", + "You may get bonus points for the following answers:\n", + "\n", + "- add exceptions https://docs.python.org/3/library/exceptions.html\n", + "- add more test cases" + ] + } + ], + "metadata": { + "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.10.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/cours-exercices/04-stacks-queues-exercises.ipynb b/cours-exercices/04-stacks-queues-exercises.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..194c35d7f9f818debe51a502034b8a932291ed12 --- /dev/null +++ b/cours-exercices/04-stacks-queues-exercises.ipynb @@ -0,0 +1,429 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "8fdc643f", + "metadata": {}, + "source": [] + }, + { + "cell_type": "markdown", + "id": "ed639e9f", + "metadata": {}, + "source": [ + "# INF TC1 - Algorithmes et structures de données\n", + "\n", + "## Exercices" + ] + }, + { + "cell_type": "markdown", + "id": "fca7f37a", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "2f1f2dcd-96a9-45ef-90a6-4ad488635679", + "metadata": {}, + "source": [ + "# Stacks and queues" + ] + }, + { + "cell_type": "markdown", + "id": "b9bd540c-dd15-49ac-bfbd-f2e758688a85", + "metadata": { + "tags": [] + }, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "03a0653e-65c2-4e79-9e83-31765cf19098", + "metadata": {}, + "source": [ + "## Exercise 1: Reverse a string using a Stack\n", + "\n", + "_Use the `Stack` below to reverse a string given as input._" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4932473d-2734-4e81-b777-ca10decfd9e8", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "class Stack:\n", + " def __init__(self):\n", + " self.items = []\n", + "\n", + " def push(self, item):\n", + " self.items.append(item)\n", + "\n", + " def pop(self):\n", + " if not self.is_empty():\n", + " return self.items.pop()\n", + "\n", + " def peek(self):\n", + " if not self.is_empty():\n", + " return self.items[-1]\n", + "\n", + " def is_empty(self):\n", + " return len(self.items) == 0" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8b77ae34-ef7c-4664-94e0-8928156f2224", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "128a37273e0e5da052abe4bf08bb1c27", + "grade": false, + "grade_id": "cell-5b0828e97507162e", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def reverse_string(s):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "63719c8e-f60c-4544-8e41-cb6380ae4bcf", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "reverse_string(\"Hello\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "81e93620-0664-4a9d-ba5f-894937c9769e", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "assert reverse_string(\"Hello\") == \"olleH\" " + ] + }, + { + "cell_type": "markdown", + "id": "81df9b1e-cfe5-4b69-96a5-c8065259cc7d", + "metadata": {}, + "source": [ + "## Exercise 2: Check if a word is a palindrom (using a Stack)\n", + "_A palindrome is a sequence of characters that reads the same forward and backward._" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cf6fbdd5-53c5-45c2-a0c5-a5ed845c4f81", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "048d788477e620bf78240329c0dd8771", + "grade": false, + "grade_id": "is_palindrome", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def is_palindrome(s):\n", + " # YOUR CODE HERE\n", + " raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "586bafba-2fbb-4833-b2e3-609db9b28fbf", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "is_palindrome(\"ABA\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d0005a10-9152-4aa5-a94b-fcbff1bd2281", + "metadata": { + "deletable": false, + "editable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "4165b33ba9b75546b0edd15216e61e4f", + "grade": true, + "grade_id": "correct_is_palindrome", + "locked": true, + "points": 0, + "schema_version": 3, + "solution": false, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "assert is_palindrome(\"ABA\")" + ] + }, + { + "cell_type": "markdown", + "id": "f767bf25-9f4f-4a0d-8cb9-b729bbec5c27", + "metadata": {}, + "source": [ + "## Exercise 3: Implement a min-heap\n", + "\n", + "Use a `PriorityQueue` to return the smallest element when using `pop` of a stack (or a queue). " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ddcccaf6-d235-4327-826f-7a62a4c23f28", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "from queue import PriorityQueue" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2da2db1e-f55d-43b4-877f-96ef944818e8", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# how to use the modue\n", + "priority_queue = PriorityQueue()\n", + "priority_queue.put((3, 'apple'))\n", + "priority_queue.put((1, 'banana'))\n", + "priority_queue.put((2, 'cherry'))\n", + "element = priority_queue.get()\n", + "print(element)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "804ea32d-5bf8-42b9-ae52-6318b26f4065", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "7f6b90fc037aa2a24fa9ce3b4dfca6dd", + "grade": false, + "grade_id": "cell-4b9a5ecdee87514e", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# YOUR CODE HERE\n", + "raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1b2d28c4-277b-44fa-b7e8-590aa00f8f70", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "min_heap = MinHeap()\n", + "min_heap.insert(5)\n", + "min_heap.insert(3)\n", + "min_heap.insert(8)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ed61bced-f000-41c6-8ecd-d669b4edb700", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "assert min_heap.pop() == 3\n", + "assert min_heap.peek() == 5\n", + "assert min_heap.peek() == 5" + ] + }, + { + "cell_type": "markdown", + "id": "a445d290-b04f-49b5-a8e7-2c6e259daf58", + "metadata": { + "tags": [] + }, + "source": [ + "## Exercise 4: Evaluate a postfix expression\n", + "\n", + "_Write a code that given the following expression, provides the following evaluation (using arthmetic operations over numerical values)._\n", + "\n", + "Expression: `\"3 4 +\"`\n", + "Evaluation: `3 + 4 = 7`\n", + "\n", + "First step: write a function `apply_operator` that applies an operation (ie + - * /) over two elements." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4cc7f805-0887-4422-b6b7-3d591d0df1fb", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "eb88296bc1de3c5dd7c68059e0a071e8", + "grade": false, + "grade_id": "cell-8c5106f02f243455", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def apply_operator(op, b, a):\n", + "# YOUR CODE HERE\n", + "raise NotImplementedError()" + ] + }, + { + "cell_type": "markdown", + "id": "e68bdf7c-ca08-4553-9874-8bd9038fd4b5", + "metadata": {}, + "source": [ + "Solution in pseudo-code:\n", + "- Split the input expression in to a list of tokens\n", + "- If not an operator\n", + " - Add the value to the stack\n", + "- If an operator \n", + " - Make sure there is enough parameters `a` and `b`\n", + " - Pop `a` and `b`\n", + " - Apply `apply_operator` on `a` and `b`\n", + " - Store the result in the stack" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e792c90d-1b38-47f5-9879-399debc934b9", + "metadata": { + "deletable": false, + "nbgrader": { + "cell_type": "code", + "checksum": "73960d3c6b85c2efc0ad8e298e2649b7", + "grade": false, + "grade_id": "cell-e9236618b265b34f", + "locked": false, + "schema_version": 3, + "solution": true, + "task": false + }, + "tags": [] + }, + "outputs": [], + "source": [ + "def evaluate_postfix(expression):\n", + "# YOUR CODE HERE\n", + "raise NotImplementedError()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ea6e4840-1b7e-4265-b37d-e8c45ea6b3ed", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "postfix_expression = \"3 4 + 2 *\"\n", + "result = evaluate_postfix(postfix_expression)\n", + "print(\"Result:\", result)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0dc4dff8-089b-46a6-a08d-f53ee2fe72c3", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "assert evaluate_postfix(\"3 4 + 2 *\") == 14\n", + "assert evaluate_postfix(\"4 2 3 5 * + *\") == 68 # (4 * (2 + (3 * 5))\n", + "assert evaluate_postfix(\"8 4 / 6 2 * +\") == 14 # ((8 / 4) + (6 * 2))" + ] + } + ], + "metadata": { + "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.10.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}