Skip to content

Commit 34b3755

Browse files
authored
Merge pull request #4 from fmipython/workshop2
Workshop2
2 parents 3fd6c91 + 9c8cad6 commit 34b3755

1 file changed

Lines changed: 332 additions & 0 deletions

File tree

Lines changed: 332 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,332 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# Workshop 2"
8+
]
9+
},
10+
{
11+
"cell_type": "markdown",
12+
"metadata": {},
13+
"source": [
14+
"## Задача 1 – `memoize`\n",
15+
"\n",
16+
"**`@memoize`**\n",
17+
"* кешира резултатите на функцията по позиционните ѝ аргументи (приемаме, че са hashable)\n",
18+
"* атрибути `hits` и `misses` на декорираната функция – колко пъти резултатът е взет от кеша и колко пъти е сметнат наново\n",
19+
"* метод `cache_clear()`, който изчиства кеша и нулира броячите\n",
20+
"* декорираната функция пази името си (`__name__`)\n"
21+
]
22+
},
23+
{
24+
"cell_type": "code",
25+
"execution_count": null,
26+
"metadata": {},
27+
"outputs": [],
28+
"source": [
29+
"def memoize(func):\n",
30+
" pass # your code here\n",
31+
"\n",
32+
"\n",
33+
"# Tests:\n",
34+
"\n",
35+
"@memoize\n",
36+
"def slow_fib(n):\n",
37+
" return n if n < 2 else slow_fib(n - 1) + slow_fib(n - 2)\n",
38+
"\n",
39+
"assert slow_fib(30) == 832040\n",
40+
"assert (slow_fib.misses, slow_fib.hits) == (31, 28)\n",
41+
"assert slow_fib(30) == 832040 and slow_fib.hits == 29\n",
42+
"slow_fib.cache_clear()\n",
43+
"assert (slow_fib.misses, slow_fib.hits) == (0, 0)\n",
44+
"slow_fib(2)\n",
45+
"assert (slow_fib.misses, slow_fib.hits) == (3, 0), \"the cache should really be empty after cache_clear\"\n",
46+
"assert slow_fib.__name__ == \"slow_fib\"\n",
47+
"\n",
48+
"\n",
49+
"\"✅ All OK!\""
50+
]
51+
},
52+
{
53+
"cell_type": "markdown",
54+
"metadata": {},
55+
"source": [
56+
"## Задача 2 – Мързеливи заявки\n",
57+
"\n",
58+
"Напишете клас `Query(iterable)`, с който да строим вериги от операции върху поредици:\n",
59+
"\n",
60+
"```python\n",
61+
"Query(range(100)).where(lambda x: x % 3 == 0).select(lambda x: x * x).skip(1).take(3).to_list()\n",
62+
"# [9, 36, 81]\n",
63+
"```\n",
64+
"\n",
65+
"**Операции** – всяка връща **нов** `Query`:\n",
66+
"* `where(predicate)` – само елементите, за които `predicate` е истина\n",
67+
"* `select(func)` – прилага `func` върху всеки елемент\n",
68+
"* `take(n)` / `skip(n)` – първите `n` елемента / всички без първите `n`\n",
69+
"* `distinct(key=None)` – премахва повторенията (сравнява по `key(x)`, ако е даден), пазейки първата поява\n",
70+
"* `chunk(size)` – групира елементите в списъци с дължина `size` (последният може да е по-къс)\n",
71+
"* `flatten()` – \"разгъва\" едно ниво на вложеност: `[[1, 2], [3]]` → `1, 2, 3`\n",
72+
"\n",
73+
"**Крайни операции:**\n",
74+
"* `for x in query`\n",
75+
"* `to_list()`, `count()`\n",
76+
"* `first(default=None)` – първият елемент или `default`, ако няма такъв\n",
77+
"\n",
78+
"⚠️ Всичко трябва да е **мързеливо** – нищо не се изчислява, докато не започнем да итерираме, и се изчислява само толкова, колкото е нужно. Това означава, че трябва да работи и с безкрайни поредици (`itertools.count()`)."
79+
]
80+
},
81+
{
82+
"cell_type": "code",
83+
"execution_count": null,
84+
"metadata": {},
85+
"outputs": [
86+
{
87+
"ename": "AttributeError",
88+
"evalue": "'NoneType' object has no attribute 'to_list'",
89+
"output_type": "error",
90+
"traceback": [
91+
"\u001b[31m---------------------------------------------------------------------------\u001b[39m",
92+
"\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)",
93+
"\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[3]\u001b[39m\u001b[32m, line 45\u001b[39m\n\u001b[32m 41\u001b[39m \n\u001b[32m 42\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m itertools\n\u001b[32m 43\u001b[39m \n\u001b[32m 44\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m Query(range(\u001b[32m100\u001b[39m)).where(\u001b[38;5;28;01mlambda\u001b[39;00m x: x % \u001b[32m3\u001b[39m == \u001b[32m0\u001b[39m).select(\u001b[38;5;28;01mlambda\u001b[39;00m x: x * x).skip(\u001b[32m1\u001b[39m).take(\u001b[32m3\u001b[39m).to_list() == [\u001b[32m9\u001b[39m, \u001b[32m36\u001b[39m, \u001b[32m81\u001b[39m]\n\u001b[32m---> \u001b[39m\u001b[32m45\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m Query([\u001b[32m3\u001b[39m, \u001b[32m1\u001b[39m, \u001b[32m3\u001b[39m, \u001b[32m2\u001b[39m, \u001b[32m1\u001b[39m]).distinct().to_list() == [\u001b[32m3\u001b[39m, \u001b[32m1\u001b[39m, \u001b[32m2\u001b[39m]\n\u001b[32m 46\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m Query([\u001b[33m\"apple\"\u001b[39m, \u001b[33m\"Avocado\"\u001b[39m, \u001b[33m\"banana\"\u001b[39m, \u001b[33m\"Blueberry\"\u001b[39m, \u001b[33m\"cherry\"\u001b[39m]).distinct(key=\u001b[38;5;28;01mlambda\u001b[39;00m s: s[\u001b[32m0\u001b[39m].lower()).to_list() == [\u001b[33m\"apple\"\u001b[39m, \u001b[33m\"banana\"\u001b[39m, \u001b[33m\"cherry\"\u001b[39m]\n\u001b[32m 47\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m Query(range(\u001b[32m7\u001b[39m)).chunk(\u001b[32m3\u001b[39m).to_list() == [[\u001b[32m0\u001b[39m, \u001b[32m1\u001b[39m, \u001b[32m2\u001b[39m], [\u001b[32m3\u001b[39m, \u001b[32m4\u001b[39m, \u001b[32m5\u001b[39m], [\u001b[32m6\u001b[39m]]\n\u001b[32m 48\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m Query([[\u001b[32m1\u001b[39m, \u001b[32m2\u001b[39m], [], [\u001b[32m3\u001b[39m]]).flatten().to_list() == [\u001b[32m1\u001b[39m, \u001b[32m2\u001b[39m, \u001b[32m3\u001b[39m]\n",
94+
"\u001b[31mAttributeError\u001b[39m: 'NoneType' object has no attribute 'to_list'"
95+
]
96+
}
97+
],
98+
"source": [
99+
"class Query:\n",
100+
" pass\n",
101+
"# Tests:\n",
102+
"\n",
103+
"import itertools\n",
104+
"\n",
105+
"assert Query(range(100)).where(lambda x: x % 3 == 0).select(lambda x: x * x).skip(1).take(3).to_list() == [9, 36, 81]\n",
106+
"assert Query([3, 1, 3, 2, 1]).distinct().to_list() == [3, 1, 2]\n",
107+
"assert Query([\"apple\", \"Avocado\", \"banana\", \"Blueberry\", \"cherry\"]).distinct(key=lambda s: s[0].lower()).to_list() == [\"apple\", \"banana\", \"cherry\"]\n",
108+
"assert Query(range(7)).chunk(3).to_list() == [[0, 1, 2], [3, 4, 5], [6]]\n",
109+
"assert Query([[1, 2], [], [3]]).flatten().to_list() == [1, 2, 3]\n",
110+
"assert Query(\"hello\").chunk(2).select(\"\".join).to_list() == [\"he\", \"ll\", \"o\"]\n",
111+
"assert Query(range(10)).where(lambda x: x > 100).first() is None\n",
112+
"assert Query(range(10)).where(lambda x: x > 100).first(default=-1) == -1\n",
113+
"assert Query(range(10)).skip(3).count() == 7\n",
114+
"assert [x for x in Query(\"abc\").select(str.upper)] == [\"A\", \"B\", \"C\"]\n",
115+
"\n",
116+
"# each operation returns a new Query, the original stays the same\n",
117+
"numbers = Query(range(5))\n",
118+
"evens = numbers.where(lambda x: x % 2 == 0)\n",
119+
"assert isinstance(evens, Query) and evens is not numbers\n",
120+
"assert numbers.to_list() == [0, 1, 2, 3, 4]\n",
121+
"assert evens.to_list() == [0, 2, 4]\n",
122+
"\n",
123+
"# laziness\n",
124+
"calls = []\n",
125+
"def spy(x):\n",
126+
" calls.append(x)\n",
127+
" return x\n",
128+
"\n",
129+
"q = Query(itertools.count()).select(spy).where(lambda x: x % 2).take(3)\n",
130+
"assert calls == [], \"nothing should be computed before iterating\"\n",
131+
"assert q.to_list() == [1, 3, 5]\n",
132+
"assert calls == [0, 1, 2, 3, 4, 5], \"only as much as needed should be computed\"\n",
133+
"\n",
134+
"assert Query(itertools.count(1)).select(lambda x: [x] * x).flatten().chunk(4).skip(2).first() == [4, 4, 5, 5]\n",
135+
"assert Query(itertools.count()).select(lambda x: x % 5).distinct().take(5).to_list() == [0, 1, 2, 3, 4]\n",
136+
"\n",
137+
"\"✅ All OK!\""
138+
]
139+
},
140+
{
141+
"cell_type": "markdown",
142+
"metadata": {},
143+
"source": [
144+
"## Задача 3 – Символни изрази\n",
145+
"\n",
146+
"Израз представяме като дърво:\n",
147+
"* число (`int` или `float`)\n",
148+
"* променлива – низ, напр. `\"x\"`\n",
149+
"* `(op, a, b)`, където `op` е `\"+\"`, `\"-\"`, `\"*\"` или `\"/\"`, а `a` и `b` са изрази\n",
150+
"* `(\"neg\", a)` – отрицание на израза `a`\n",
151+
"\n",
152+
"Например $ 2 \\cdot x + (-y) $ е `(\"+\", (\"*\", 2, \"x\"), (\"neg\", \"y\"))`.\n",
153+
"\n",
154+
"Напишете следните функции, като използвате **`match`**:\n",
155+
"\n",
156+
"**`evaluate(expr, env)`** – пресмята израза, като стойностите на променливите са в речника `env`. Връща `None`, ако изразът е невалиден, има непозната променлива или деление на 0.\n",
157+
"\n",
158+
"**`to_string(expr)`** – връща израза като низ. Всяка бинарна операция е в скоби: `\"((2 * x) + -y)\"`. Отрицанието е `\"-\"` пред израза.\n",
159+
"\n",
160+
"**`simplify(expr)`** – опростява израза рекурсивно (първо децата, после текущия възел) по следните правила:\n",
161+
"* операция само върху числа се пресмята (с изключение на деление на 0 – тогава изразът остава какъвто е)\n",
162+
"* `x + 0`, `0 + x`, `x - 0`, `x * 1`, `1 * x`, `x / 1` → `x`\n",
163+
"* `x * 0`, `0 * x`, `0 / x` → `0`\n",
164+
"* `x - x` → `0` и `x / x` → `1` (когато двете страни са еднакви изрази)\n",
165+
"* `0 - x` → `(\"neg\", x)`\n",
166+
"* `(\"neg\", (\"neg\", x))` → `x`"
167+
]
168+
},
169+
{
170+
"cell_type": "code",
171+
"execution_count": null,
172+
"metadata": {},
173+
"outputs": [],
174+
"source": [
175+
"def evaluate(expr, env):\n",
176+
" pass # your code here\n",
177+
"\n",
178+
"\n",
179+
"def to_string(expr):\n",
180+
" pass # your code here\n",
181+
"\n",
182+
"\n",
183+
"def simplify(expr):\n",
184+
" pass # your code here\n",
185+
"\n",
186+
"\n",
187+
"# Tests:\n",
188+
"\n",
189+
"expr = (\"+\", (\"*\", 2, \"x\"), (\"neg\", \"y\"))\n",
190+
"env = {\"x\": 5, \"y\": 3}\n",
191+
"\n",
192+
"assert evaluate(42, {}) == 42\n",
193+
"assert evaluate(\"x\", env) == 5\n",
194+
"assert evaluate(expr, env) == 7\n",
195+
"assert evaluate((\"/\", \"x\", 2), env) == 2.5\n",
196+
"assert evaluate((\"-\", (\"neg\", \"x\"), (\"*\", \"y\", \"y\")), env) == -14\n",
197+
"assert evaluate(\"z\", env) is None, \"unknown variable\"\n",
198+
"assert evaluate((\"/\", 1, (\"-\", \"x\", 5)), env) is None, \"division by zero\"\n",
199+
"assert evaluate((\"%\", 1, 2), env) is None, \"unknown operation\"\n",
200+
"assert evaluate((\"+\", 1), env) is None, \"wrong number of arguments\"\n",
201+
"assert evaluate((\"+\", 1, (\"+\", \"x\", \"z\")), env) is None, \"errors should propagate\"\n",
202+
"\n",
203+
"assert to_string(expr) == \"((2 * x) + -y)\"\n",
204+
"assert to_string((\"neg\", (\"-\", \"a\", 1.5))) == \"-(a - 1.5)\"\n",
205+
"assert to_string(\"x\") == \"x\" and to_string(7) == \"7\"\n",
206+
"\n",
207+
"assert simplify((\"+\", 2, 3)) == 5\n",
208+
"assert simplify((\"*\", (\"+\", 1, 1), (\"-\", 10, 7))) == 6\n",
209+
"assert simplify((\"+\", \"x\", 0)) == \"x\"\n",
210+
"assert simplify((\"*\", 1, (\"+\", \"x\", (\"*\", \"y\", 0)))) == \"x\"\n",
211+
"assert simplify((\"*\", (\"+\", \"x\", \"y\"), (\"-\", 3, 3))) == 0\n",
212+
"assert simplify((\"-\", (\"+\", \"x\", 1), (\"+\", \"x\", 1))) == 0\n",
213+
"assert simplify((\"/\", (\"*\", \"a\", \"b\"), (\"*\", \"a\", \"b\"))) == 1\n",
214+
"assert simplify((\"-\", 0, \"x\")) == (\"neg\", \"x\")\n",
215+
"assert simplify((\"neg\", (\"neg\", (\"+\", \"x\", 0)))) == \"x\"\n",
216+
"assert simplify((\"neg\", (\"+\", 2, 3))) == -5\n",
217+
"assert simplify((\"/\", \"x\", (\"-\", 2, 2))) == (\"/\", \"x\", 0), \"division by zero stays\"\n",
218+
"assert simplify((\"+\", (\"*\", 2, \"x\"), (\"*\", 3, 4))) == (\"+\", (\"*\", 2, \"x\"), 12)\n",
219+
"assert simplify(\"x\") == \"x\" and simplify(3.5) == 3.5\n",
220+
"\n",
221+
"big = (\"+\", (\"*\", (\"-\", \"x\", 0), (\"/\", \"y\", \"y\")), (\"-\", 0, (\"*\", 0, \"z\")))\n",
222+
"assert simplify(big) == \"x\"\n",
223+
"assert evaluate(big, {\"x\": 4, \"y\": 2, \"z\": 9}) == evaluate(simplify(big), {\"x\": 4}) == 4\n",
224+
"\n",
225+
"\"✅ All OK!\""
226+
]
227+
},
228+
{
229+
"cell_type": "markdown",
230+
"metadata": {},
231+
"source": [
232+
"## Задача 4 – Отчет за продажби\n",
233+
"\n",
234+
"Дадени са поръчки като `namedtuple`-и `Order(customer, product, quantity, price, month)`.\n",
235+
"\n",
236+
"Напишете функциите **без нито един `for`/`while` цикъл** извън comprehensions – само с comprehensions, `map`, `filter`, `functools.reduce`, `sorted`, `zip`, `any`, `all`, `sum`, `max` и т.н.\n",
237+
"\n",
238+
"* `revenue_by_customer(orders)` – речник `клиент → общ приход` (`quantity * price`)\n",
239+
"* `top_products(orders, n)` – списък от `n` наредени двойки `(продукт, общо количество)` с най-голямо количество; при равенство – по име възходящо\n",
240+
"* `loyal_customers(orders)` – сортиран списък от клиентите, които имат поръчка във **всеки** от месеците, които се срещат в данните\n",
241+
"* `monthly_growth(orders)` – списък от тройки `(месец, приход, промяна)` по месеци възходящо, където `промяна` е процентната промяна спрямо предходния месец, закръглена до 1 знак (`None` за първия месец)\n",
242+
"* `best_month_per_product(orders)` – речник `продукт → месецът с най-голямо количество продадени` (при равенство – по-ранният месец)"
243+
]
244+
},
245+
{
246+
"cell_type": "code",
247+
"execution_count": null,
248+
"metadata": {},
249+
"outputs": [],
250+
"source": [
251+
"from collections import namedtuple\n",
252+
"from functools import reduce\n",
253+
"\n",
254+
"Order = namedtuple(\"Order\", [\"customer\", \"product\", \"quantity\", \"price\", \"month\"])\n",
255+
"\n",
256+
"\n",
257+
"def revenue_by_customer(orders):\n",
258+
" pass # your code here\n",
259+
"\n",
260+
"\n",
261+
"def top_products(orders, n):\n",
262+
" pass # your code here\n",
263+
"\n",
264+
"\n",
265+
"def loyal_customers(orders):\n",
266+
" pass # your code here\n",
267+
"\n",
268+
"\n",
269+
"def monthly_growth(orders):\n",
270+
" pass # your code here\n",
271+
"\n",
272+
"\n",
273+
"def best_month_per_product(orders):\n",
274+
" pass # your code here\n",
275+
"\n",
276+
"\n",
277+
"# Tests:\n",
278+
"\n",
279+
"orders = [\n",
280+
" Order(\"ana\", \"coffee\", 2, 5.0, 1),\n",
281+
" Order(\"bob\", \"tea\", 3, 3.0, 1),\n",
282+
" Order(\"ana\", \"cake\", 1, 8.0, 2),\n",
283+
" Order(\"cvetan\", \"coffee\", 4, 5.0, 2),\n",
284+
" Order(\"bob\", \"coffee\", 1, 5.0, 2),\n",
285+
" Order(\"ana\", \"tea\", 5, 3.0, 3),\n",
286+
" Order(\"bob\", \"cake\", 2, 8.0, 3),\n",
287+
" Order(\"cvetan\", \"tea\", 1, 3.0, 3),\n",
288+
"]\n",
289+
"\n",
290+
"assert revenue_by_customer(orders) == {\"ana\": 33.0, \"bob\": 30.0, \"cvetan\": 23.0}\n",
291+
"assert revenue_by_customer([]) == {}\n",
292+
"\n",
293+
"assert top_products(orders, 2) == [(\"tea\", 9), (\"coffee\", 7)]\n",
294+
"assert top_products(orders, 10) == [(\"tea\", 9), (\"coffee\", 7), (\"cake\", 3)]\n",
295+
"assert top_products(orders + [Order(\"ana\", \"beer\", 7, 2.0, 3)], 3) == [(\"tea\", 9), (\"beer\", 7), (\"coffee\", 7)]\n",
296+
"\n",
297+
"assert loyal_customers(orders) == [\"ana\", \"bob\"]\n",
298+
"assert loyal_customers(orders[:2]) == [\"ana\", \"bob\"]\n",
299+
"assert loyal_customers([]) == []\n",
300+
"\n",
301+
"assert monthly_growth(orders) == [(1, 19.0, None), (2, 33.0, 73.7), (3, 34.0, 3.0)]\n",
302+
"assert monthly_growth(orders[:1]) == [(1, 10.0, None)]\n",
303+
"\n",
304+
"assert best_month_per_product(orders) == {\"coffee\": 2, \"tea\": 3, \"cake\": 3}\n",
305+
"assert best_month_per_product(orders + [Order(\"bob\", \"cake\", 1, 8.0, 2)]) == {\"coffee\": 2, \"tea\": 3, \"cake\": 2}, \"earlier month wins ties\"\n",
306+
"\n",
307+
"\"✅ All OK!\""
308+
]
309+
}
310+
],
311+
"metadata": {
312+
"kernelspec": {
313+
"display_name": ".venv (3.14.3)",
314+
"language": "python",
315+
"name": "python3"
316+
},
317+
"language_info": {
318+
"codemirror_mode": {
319+
"name": "ipython",
320+
"version": 3
321+
},
322+
"file_extension": ".py",
323+
"mimetype": "text/x-python",
324+
"name": "python",
325+
"nbconvert_exporter": "python",
326+
"pygments_lexer": "ipython3",
327+
"version": "3.14.3"
328+
}
329+
},
330+
"nbformat": 4,
331+
"nbformat_minor": 4
332+
}

0 commit comments

Comments
 (0)