Skip to content

Commit 237bdf0

Browse files
committed
Day_5 Edits
1 parent 34f5c10 commit 237bdf0

14 files changed

Lines changed: 510 additions & 21 deletions

‎data/food.csv‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
Food Group,Food Name
2+
Grains and Cereals,Rice
3+
Grains and Cereals,Pasta
4+
Grains and Cereals,Oats
5+
Grains and Cereals,Quinoa
6+
Grains and Cereals,Barley
7+
Fruits,Apple
8+
Fruits,Banana
9+
Fruits,Orange
10+
Fruits,Strawberries
11+
Fruits,Blueberries
12+
Vegetables,Broccoli
13+
Vegetables,Carrots
14+
Vegetables,Spinach
15+
Vegetables,Tomatoes
16+
Vegetables,Cucumbers
17+
Proteins,Chicken
18+
Proteins,Beef
19+
Proteins,Salmon
20+
Proteins,Beans
21+
Proteins,Tofu
22+
Dairy,Milk
23+
Dairy,Yogurt
24+
Dairy,Cheese
25+
Dairy,Butter
26+
Dairy,Sour Cream
27+
Sweets,Chocolate
28+
Sweets,Ice Cream
29+
Sweets,Cookies
30+
Sweets,Pie
31+
Sweets,Cake
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import bisect
2+
3+
# The bisect module in Python provides functions to perform binary searches
4+
# on sorted sequences. It allows you to efficiently find the insertion point
5+
# for a new element in a sorted list or to locate an element in a sorted
6+
# list.
7+
8+
# Sorted list of numbers
9+
sorted_list = [1, 3, 5, 7, 9]
10+
11+
# Inserting an element while maintaining the sorted order
12+
element_to_insert = 4
13+
index_to_insert = bisect.bisect(sorted_list, element_to_insert)
14+
sorted_list.insert(index_to_insert, element_to_insert)
15+
print("List after inserting 4:", sorted_list) # Output: [1, 3, 4, 5, 7, 9]
16+
17+
# Finding the insertion point for a new element
18+
new_element = 6
19+
insertion_point = bisect.bisect(sorted_list, new_element)
20+
print(f"Insert {new_element} at index {insertion_point} to maintain sorting.")
21+
22+
# Using insort to insert an element while maintaining the sorted order
23+
bisect.insort(sorted_list, 2)
24+
25+
# Output: [1, 2, 3, 4, 5, 7, 9]
26+
print("List after inserting 2 using insort:", sorted_list)
27+
28+
# Finding an element's position in the sorted list
29+
element_to_find = 5
30+
position = bisect.bisect_left(sorted_list, element_to_find)
31+
if sorted_list[position] == element_to_find:
32+
print(f"{element_to_find} found at index {position}.")
33+
else:
34+
print(f"{element_to_find} not found in the list.")
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""comprehensions demo"""
2+
3+
from itertools import islice
4+
from pathlib import Path
5+
from random import randint
6+
import csv
7+
8+
9+
def list_comprehension() -> None:
10+
"""list comprehension"""
11+
12+
even_nums = [x for x in range(10) if (x % 2 == 0)]
13+
print(even_nums)
14+
15+
double_nums = [x * 2 for x in range(2)]
16+
print(double_nums)
17+
18+
19+
def dictionary_comprehension() -> None:
20+
"""dictionary comprehension"""
21+
22+
food_groups = None
23+
24+
with Path("data", "food.csv").open(encoding="UTF-8") as food_file:
25+
food_groups = {
26+
food[1]: food[0] for food in csv.reader(islice(food_file, 1, 6))
27+
}
28+
29+
print(food_groups)
30+
31+
32+
def set_comprehension() -> None:
33+
"""set comprehension"""
34+
35+
nums = [randint(0, 9) for _ in range(50)]
36+
37+
unique_nums = {num for num in nums}
38+
39+
print(nums)
40+
print(unique_nums)
41+
print(type(unique_nums))
42+
43+
44+
def generator_comprehension() -> None:
45+
# example map (x * 3) and filter (x % 2 == 0)
46+
triple_nums = (x * 3 for x in range(10) if x % 2 == 0)
47+
48+
print(type(triple_nums))
49+
print(list(triple_nums))
50+
51+
52+
def main() -> None:
53+
# list_comprehension()
54+
# dictionary_comprehension()
55+
# set_comprehension()
56+
generator_comprehension()
57+
58+
59+
if __name__ == "__main__":
60+
main()
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import heapq
2+
3+
# heapq is a module in Python that provides a collection of heap queue
4+
# algorithms. It allows you to efficiently manipulate and maintain a
5+
# heap data structure, which is a specialized tree-based structure that
6+
# satisfies the heap property (either min-heap or max-heap).
7+
8+
# A min-heap and a max-heap are both specialized forms of binary heap data
9+
# structures used in computer science and data processing for efficient
10+
# management of elements with respect to their values. They are often used
11+
# in priority queues, heapsort, and various other algorithms.
12+
13+
# Here are the key differences between a min-heap and a max-heap:
14+
15+
# **Min-Heap:**
16+
# 1. In a min-heap, the value of each node (including the root) is less than
17+
# or equal to the values of its children.
18+
# 2. The smallest element is at the root of the heap, which makes it suitable
19+
# for finding the minimum element quickly.
20+
# 3. Min-heaps are used in algorithms where you need to extract the smallest
21+
# element efficiently, such as Dijkstra's algorithm for finding the shortest
22+
# path in a graph.
23+
24+
# **Max-Heap:**
25+
# 1. In a max-heap, the value of each node (including the root) is greater
26+
# than or equal to the values of its children.
27+
# 2. The largest element is at the root of the heap, which makes it suitable
28+
# for finding the maximum element quickly.
29+
# 3. Max-heaps are used in algorithms where you need to extract the largest
30+
# element efficiently, such as heapsort, which is an in-place sorting
31+
# algorithm.
32+
33+
# Both min-heaps and max-heaps are typically implemented as binary trees,
34+
# with the heap property enforced such that the parent node's value is
35+
# compared with its children in a way that maintains the desired ordering
36+
# (minimum or maximum).
37+
38+
# Here's a visual representation of a min-heap and a max-heap:
39+
40+
# **Min-Heap:**
41+
42+
# ```
43+
# 1
44+
# / \
45+
# 2 3
46+
# / \ / \
47+
# 4 5 6 7
48+
# ```
49+
50+
# **Max-Heap:**
51+
52+
# ```
53+
# 7
54+
# / \
55+
# 5 6
56+
# / \ / \
57+
# 2 4 3 1
58+
# ```
59+
60+
# In summary, min-heaps and max-heaps are used for maintaining ordered
61+
# collections of elements, with the primary difference being the order
62+
# in which elements are organized. Min-heaps prioritize smaller elements,
63+
# while max-heaps prioritize larger elements.
64+
65+
# Create an empty list to represent a min-heap
66+
min_heap = []
67+
68+
# Insert elements into the min-heap
69+
elements = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
70+
for element in elements:
71+
heapq.heappush(min_heap, element)
72+
73+
print("Min-Heap after inserting elements:", min_heap)
74+
75+
# Get the smallest element (root of the min-heap)
76+
smallest = heapq.heappop(min_heap)
77+
print("Smallest element:", smallest)
78+
79+
# Insert a new element into the min-heap
80+
new_element = 0
81+
heapq.heappush(min_heap, new_element)
82+
print("Min-Heap after inserting", new_element, ":", min_heap)
83+
84+
# Find the smallest element without removing it
85+
smallest = heapq.heappop(min_heap)
86+
print("Smallest element (without removal):", smallest)
87+
88+
# Convert a list into a valid min-heap in-place
89+
unordered_list = [7, 8, 2, 3, 1]
90+
heapq.heapify(unordered_list)
91+
print("Min-Heap created from an unordered list:", unordered_list)
92+
93+
# Find the n largest elements in a list using nlargest
94+
n_largest = heapq.nlargest(3, elements)
95+
print("3 largest elements:", n_largest)
96+
97+
# Find the n smallest elements in a list using nsmallest
98+
n_smallest = heapq.nsmallest(3, elements)
99+
print("3 largest elements:", n_smallest)
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
from typing import TypedDict
2+
from dataclasses import dataclass
3+
4+
command = input("Enter a command > ")
5+
operand = float(input("Enter an operand > "))
6+
7+
# Equivalent of a switch statement
8+
9+
# match command:
10+
# case "add":
11+
# print(operand + operand)
12+
# case "subtract":
13+
# print(operand - operand)
14+
# case "multiply":
15+
# print(operand * operand)
16+
# case "divide":
17+
# print(operand / operand)
18+
# case _:
19+
# print("Invalid command")
20+
21+
# Multiple values match a case
22+
23+
# match command:
24+
# case "add" | "subtract":
25+
# print(f"do {command} numbers")
26+
# case _:
27+
# print("Invalid command")
28+
29+
# Conditional if statements in a case
30+
31+
# match command:
32+
# case "divide" if operand == 0:
33+
# print("Cannot divide by zero")
34+
# case "add" | "subtract" | "multiply" | "divide":
35+
# print(f"do {command} numbers")
36+
# case _:
37+
# print("Invalid command")
38+
39+
# Match list objects and capture values in variables
40+
41+
# history = [["subtract", 10], ["add", 20], ["multiply", 30], ["divide", 40]]
42+
43+
# for operation in history:
44+
# match operation:
45+
# case ["add", value]:
46+
# print(f"Adding {value}")
47+
# case ["subtract", value]:
48+
# print(f"Subtracting {value}")
49+
# case ["multiply", value]:
50+
# print(f"Multiplying {value}")
51+
# case ["divide", value]:
52+
# print(f"Dividing {value}")
53+
54+
# Match case with dictionary objects
55+
56+
# class HistoryEntry(TypedDict):
57+
# id: int
58+
# operation: str
59+
# value: int
60+
61+
62+
# history2: list[HistoryEntry] = [
63+
# {"id": 1, "operation": "subtract", "value": 10},
64+
# {"id": 2, "operation": "add", "value": 20},
65+
# {"id": 3, "operation": "multiply", "value": 30},
66+
# {"id": 4, "operation": "divide", "value": 40},
67+
# ]
68+
69+
# for operation2 in history2:
70+
# match operation2:
71+
# case {"id": op_id, "operation": "add", "value": op_value}:
72+
# print(f"Op Id: {op_id}: Adding {op_value}")
73+
74+
# Match case with regular objects
75+
76+
77+
@dataclass
78+
class HistoryEntry2:
79+
id: int
80+
operation: str
81+
value: int
82+
83+
84+
history3: list[HistoryEntry2] = [
85+
HistoryEntry2(1, "subtract", 10),
86+
HistoryEntry2(2, "add", 20),
87+
HistoryEntry2(3, "multiply", 30),
88+
HistoryEntry2(4, "divide", 40),
89+
]
90+
91+
for operation3 in history3:
92+
match operation3:
93+
case HistoryEntry2(op_id, "add", op_value):
94+
print(f"Op Id: {op_id}: Adding {op_value}")
95+
case HistoryEntry2(op_id, "subtract", op_value):
96+
print(f"Op Id: {op_id}: Subtracting {op_value}")
97+
case HistoryEntry2(op_id, "multiply", op_value):
98+
print(f"Op Id: {op_id}: Multiplying {op_value}")
99+
case HistoryEntry2(op_id, "divide", op_value):
100+
print(f"Op Id: {op_id}: Dividing {op_value}")
101+
case _:
102+
print("Invalid operation")
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from typing import Callable, Any
2+
3+
4+
class App:
5+
def __init__(self) -> None:
6+
self.__routes: dict = {}
7+
8+
def print_routes(self) -> None:
9+
print(self.__routes)
10+
11+
def route(self, path: str) -> Callable:
12+
print(f"calling route: {path}")
13+
14+
def wrapper(fn: Callable[..., Any]) -> Callable[..., Any]:
15+
print(f"calling wrapper: {path}")
16+
self.__routes[path] = fn
17+
18+
def inner(*args: Any, **kwargs: Any) -> Any:
19+
print(f"path: {path}")
20+
return fn(*args, **kwargs)
21+
22+
return inner
23+
24+
return wrapper
25+
26+
def run(self, path: str, *args: Any, **kwargs: Any) -> Any:
27+
fn = self.__routes[path]
28+
return fn(*args, **kwargs)
29+
30+
31+
app = App()
32+
33+
34+
@app.route("/add")
35+
def add(a: int, b: int) -> int:
36+
return a + b
37+
38+
39+
@app.route("/sub")
40+
def subtract(a: int, b: int) -> int:
41+
return a - b
42+
43+
44+
app.print_routes()
45+
46+
47+
print(app.run("/add", 1, 2))
48+
print(app.run("/sub", 1, 2))

‎demos/code_techniques/reverse.py‎

Whitespace-only changes.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from typing import Type, Any
2+
3+
def add_hello(cls: Type) -> Type:
4+
5+
6+

0 commit comments

Comments
 (0)