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

Create 03-stacks-queues-exercises.ipynb

parent 7b0fa67d
Branches
No related tags found
No related merge requests found
%% Cell type:markdown id:5ce21950 tags:
NAME:
%% Cell type:markdown id:2f1f2dcd-96a9-45ef-90a6-4ad488635679 tags:
# UE5 Fundamentals of Algorithms
# Lab 3: Stacks and Queues
%% Cell type:markdown id:b9bd540c-dd15-49ac-bfbd-f2e758688a85 tags:
---
%% Cell type:markdown id:a18516d6-24ae-4e5c-afb7-43a4435ea868 tags:
<details style="border: 1px">
<summary> How to use those notebooks</summary>
For each of the following questions:
- In the `# YOUR CODE HERE` cell, remove `raise NotImplementedError()` to write your code
- Write an example of use of your code or make sure the given examples and tests pass
- Add extra tests in the `#Tests` cell
</details>
%% Cell type:markdown id:7fdd7e6b-da89-4100-8241-0b0d47caa3ed tags:
Course reminders:
<img src="./figures/stacks-queues.png" style="width:500px">
- `stacks` follow the Last-In, First-Out (LIFO) principle
- `queues`follows the First-In, First-Out (FIFO) principle
They have the following operations:
- `empty()`: Checks for emptiness.
- `full()`: Checks if it's full (if a maximum size was provided during creation).
- `get()`: Returns (and removes) an element.
- `push(element)`: Adds an element.
- `size()`: Returns the size of the list.
- `peek()`: Returns an element (without removing it).
- `clear()`: Empties the list.
- `contains(element)`: Checks if a specified element has been added.
- `index(element)`: Finds the index of a specified element.
- `remove(element)`: Removes a specific element (if present).
%% Cell type:markdown id:d389441b-f86b-41c6-b7ec-6dd89eb61af6 tags:
## Exercise 1: Implement a Stack
Use the `Stack` object below and implement the above operations.
%% Cell type:code id:146beb1c-fcfa-43cb-9718-7bb61e6201bc tags:
``` python
class Stack:
def __init__(self, max_size=1000):
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:code id:5afc8b1f-2708-4289-8d54-c6bdada4d184 tags:
``` python
# Example of use
s = Stack()
s.push(10)
s.push(20)
s.get() == 20
s.get() == 10
```
%% Cell type:markdown id:6f37285b-a4e6-4261-9c10-3e98f4ef1f08 tags:
Compare with the `queue` [package](https://docs.python.org/3/library/queue.html) from Python
```python
import queue
q1 = queue.Queue()
```
%% Cell type:code id:d7ff762d-e812-433b-8f57-56004477278f tags:
``` python
import queue
# Tests
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:markdown id:03a0653e-65c2-4e79-9e83-31765cf19098 tags:
## Exercise 2: Reverse a string
Use the `Stack` data structure to reverse a string `s` given as input.
%% 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
# Example of use
reverse_string("Hello")
```
%% Cell type:code id:81e93620-0664-4a9d-ba5f-894937c9769e tags:
``` python
# Tests
assert reverse_string("Hello") == "Hello"[::-1]
assert reverse_string("Hello") == "".join(reversed("Hello"))
```
%% Cell type:markdown id:81df9b1e-cfe5-4b69-96a5-c8065259cc7d tags:
## Exercise 3: Check if a word is a palindrom
Use the `Stack` to check if a sequence of characters 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:f1e3d451-9ac1-4551-9cd5-c3024133495c tags:
``` python
# Example of use
is_palindrome("ABA")
```
%% Cell type:code id:586bafba-2fbb-4833-b2e3-609db9b28fbf tags:
``` python
# Tests
assert is_palindrome("ABA")
assert not is_palindrome("ABAB")
```
%% Cell type:markdown id:7a6c95d6-266e-4742-bfef-8b1f2dda4164 tags:
## Exercise 4: Store unique elements only
Use the `Stack` to create a new class that inherits it and call it `StackUnique` to only store unique values (ie if a value has already been added do not add it).
%% Cell type:code id:cab518b1-4d59-45d2-9e69-ae95458eeac5 tags:
``` python
class StackUnique(Stack):
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:code id:53ac7eb2-295e-469b-b63b-ffbe876ff620 tags:
``` python
# Usage example
s = StackUnique()
s.push(1)
s.push(1)
s.get()
s.get() if not s.empty() else print("no more value")
```
%% Cell type:code id:12847b9d-947f-4181-84cc-d2726199269b tags:
``` python
# Tests
s = StackUnique()
s.push(1)
s.push(1)
assert s.get() == 1
assert s.empty()
```
%% Cell type:markdown id:882884c2-1918-4224-9124-81bc55e43d4e tags:
## Exercise 5: Check if correct number and order of brackets
To verify if a string contains balanced brackets in the correct order, we can use a `Stack` to check if each opening bracket has a matching closing bracket and that they are correctly nested.
%% Cell type:code id:804ea32d-5bf8-42b9-ae52-6318b26f4065 tags:
``` python
def is_balanced(s):
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:code id:d7c86615-db59-4cff-aa16-32c3928fbbae tags:
``` python
# Usage example
is_balanced("([])")
```
%% Cell type:code id:aab38745-f306-4015-bcff-563f3c1b4166 tags:
``` python
# Tests
assert is_balanced("([])")
assert is_balanced("([{}])")
assert not is_balanced("(]")
assert is_balanced("(([]){})")
assert not is_balanced("({[})")
```
%% Cell type:markdown id:91792d87-9c2b-4a4f-ad6e-1980bb76b06e tags:
## Exercice 6: Merge overlapping intervals
Given a list of intervals, where each interval is represented as a list `[start, end]`, your task is to merge all overlapping intervals. Overlapping intervals should be merged into one interval with the start as the minimum of both intervals starts and the end as the maximum of both intervals ends. For example, with input `[[1, 3], [2, 6], [8, 10], [15, 18], [17, 20]]` you may return as output `[[1, 6], [8, 10], [15, 20]]` where 2 pairs intervals have been marged. Here is a way to solve this problem:
1. Check if the input list of intervals is empty (if it is, return an empty list)
2. Sort the intervals by their starting times.
3. Create an empty stack that will contain the merged intervals.
4. Iterate through each interval:
- If the stack is empty or the current interval does not overlap with the last interval in the stack, push the current interval onto the stack.
- If there is an overlap, pop the last interval from the stack, merge it with the current interval, and push the merged interval back onto the stack.
5. Convert the stack to a list and return the merged intervals.
%% Cell type:code id:a81eb460-4622-44cd-81b9-c89be4bb5b48 tags:
``` python
def merge_intervals(intervals):
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:code id:8b02e24d-d498-40f3-a0f9-d6e0e8ad0d2e tags:
``` python
# Usage example
intervals = [[1, 3], [2, 6], [8, 10], [15, 18], [17, 20]]
merged = merge_intervals(intervals)
print("Merged Intervals:", merged)
```
%% Cell type:code id:c04dfd85-04c7-43e5-8aa5-b4774e253bf4 tags:
``` python
# Tests
assert merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18], [17, 20]]) == [[1, 6], [8, 10], [15, 20]]
assert merge_intervals([[1, 2]]) == [[1, 2]]
```
%% Cell type:markdown id:a445d290-b04f-49b5-a8e7-2c6e259daf58 tags:
## Exercise 7 (BONUS): 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
# 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 *"
print(evaluate_postfix(postfix_expression))
```
%% 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))
```
%% Cell type:code id:18f4fdcb-50be-4219-b14c-1e9a902e22db tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment