Skip to content
Snippets Groups Projects
Commit 74268f47 authored by Romain Vuillemot's avatar Romain Vuillemot
Browse files

ajout exercices de cours

parent 1e49e1da
Branches
No related tags found
No related merge requests found
%% 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
```
This diff is collapsed.
%% 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))
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment