Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
Loading items

Target

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