├── Pandas
├── .ipynb_checkpoints
│ ├── Concat-Merge-Groupby-checkpoint.ipynb
│ └── Pandas_Intro-checkpoint.ipynb
├── Concat-Merge-Groupby.ipynb
└── Pandas_Intro.ipynb
├── Python
├── .ipynb_checkpoints
│ ├── Python_Part1-checkpoint.ipynb
│ ├── Python_Part2-checkpoint.ipynb
│ ├── Python_Part3-checkpoint.ipynb
│ ├── Python_Part4-checkpoint.ipynb
│ ├── Python_Part5-checkpoint.ipynb
│ └── Python_Part6-checkpoint.ipynb
├── Python_Part1.ipynb
├── Python_Part2.ipynb
├── Python_Part3.ipynb
├── Python_Part4.ipynb
├── Python_Part5.ipynb
└── Python_Part6.ipynb
└── README.md
/Python/.ipynb_checkpoints/Python_Part2-checkpoint.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "application/vnd.databricks.v1+cell": {
7 | "inputWidgets": {},
8 | "nuid": "85b36ae8-5cea-48da-84f7-4bbd359b6fe9",
9 | "showTitle": false,
10 | "title": ""
11 | }
12 | },
13 | "source": [
14 | "# Python for Data Science and Machine Learning - Part 2\n",
15 | "\n",
16 | "----\n",
17 | "\n",
18 | "\n",
19 | "**Dictionary continued...**\n",
20 | "\n",
21 | "Other ways to create dictionaries"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": 1,
27 | "metadata": {
28 | "application/vnd.databricks.v1+cell": {
29 | "inputWidgets": {},
30 | "nuid": "2493a889-ea91-43df-b65e-9e859cea4e03",
31 | "showTitle": false,
32 | "title": ""
33 | }
34 | },
35 | "outputs": [
36 | {
37 | "data": {
38 | "text/plain": [
39 | "{'model': 'Beetle', 'year': 2021, 'maker': 'Volkswagon'}"
40 | ]
41 | },
42 | "execution_count": 1,
43 | "metadata": {},
44 | "output_type": "execute_result"
45 | }
46 | ],
47 | "source": [
48 | "# Create a dictionary with list of zipped keys/values\n",
49 | "keys = ['model', 'year', 'maker']\n",
50 | "values = ['Beetle', 2021, 'Volkswagon']\n",
51 | "\n",
52 | "D = dict(zip(keys,values))\n",
53 | "D"
54 | ]
55 | },
56 | {
57 | "cell_type": "markdown",
58 | "metadata": {
59 | "application/vnd.databricks.v1+cell": {
60 | "inputWidgets": {},
61 | "nuid": "3a29eb64-b946-4746-8939-b5c803737ac8",
62 | "showTitle": false,
63 | "title": ""
64 | }
65 | },
66 | "source": [
67 | "Note: Keys must be unique. If a key is specified more than once while the creation of a dictionary, the last value for that key becomes the associated value."
68 | ]
69 | },
70 | {
71 | "cell_type": "code",
72 | "execution_count": 2,
73 | "metadata": {
74 | "application/vnd.databricks.v1+cell": {
75 | "inputWidgets": {},
76 | "nuid": "326a15da-694d-4c5e-8b09-7389cecd47fd",
77 | "showTitle": false,
78 | "title": ""
79 | }
80 | },
81 | "outputs": [
82 | {
83 | "name": "stdout",
84 | "output_type": "stream",
85 | "text": [
86 | "{'model': 'Jetta', 'year': 2021}\n"
87 | ]
88 | }
89 | ],
90 | "source": [
91 | "D = {'model': 'Beetle',\n",
92 | " 'year': 2021,\n",
93 | " 'model': 'Jetta'}\n",
94 | "print(D)"
95 | ]
96 | },
97 | {
98 | "cell_type": "markdown",
99 | "metadata": {
100 | "application/vnd.databricks.v1+cell": {
101 | "inputWidgets": {},
102 | "nuid": "41994238-4e17-42d0-8c0c-d639228fa3de",
103 | "showTitle": false,
104 | "title": ""
105 | }
106 | },
107 | "source": [
108 | "Create a dictionary with default values for each key. The `fromkeys()` method offers a way to do this."
109 | ]
110 | },
111 | {
112 | "cell_type": "code",
113 | "execution_count": 3,
114 | "metadata": {
115 | "application/vnd.databricks.v1+cell": {
116 | "inputWidgets": {},
117 | "nuid": "97531796-c422-4385-b23d-6907df464505",
118 | "showTitle": false,
119 | "title": ""
120 | }
121 | },
122 | "outputs": [
123 | {
124 | "data": {
125 | "text/plain": [
126 | "{'x': 0, 'y': 0, 'z': 0}"
127 | ]
128 | },
129 | "execution_count": 3,
130 | "metadata": {},
131 | "output_type": "execute_result"
132 | }
133 | ],
134 | "source": [
135 | "# Initialize a dictionary with default value '0' for each key\n",
136 | "keys = ['x', 'y', 'z']\n",
137 | "defaultValue = 0\n",
138 | "\n",
139 | "D = dict.fromkeys(keys,defaultValue)\n",
140 | "D"
141 | ]
142 | },
143 | {
144 | "cell_type": "code",
145 | "execution_count": 4,
146 | "metadata": {
147 | "application/vnd.databricks.v1+cell": {
148 | "inputWidgets": {},
149 | "nuid": "17910056-6bc5-4f05-9160-fff5d50bd936",
150 | "showTitle": false,
151 | "title": ""
152 | }
153 | },
154 | "outputs": [
155 | {
156 | "name": "stdout",
157 | "output_type": "stream",
158 | "text": [
159 | "{'a': [1, 2, 3], 'b': {1, 2, 3}}\n",
160 | "{'a': [1, 2], 'b': [1, 2], 'c': [1, 2]}\n"
161 | ]
162 | }
163 | ],
164 | "source": [
165 | "D = {'a':[1,2,3],\n",
166 | " 'b':{1,2,3}}\n",
167 | "print (D)\n",
168 | "\n",
169 | "# duplicate values\n",
170 | "D = {'a':[1,2],\n",
171 | " 'b':[1,2],\n",
172 | " 'c':[1,2]}\n",
173 | "print (D)"
174 | ]
175 | },
176 | {
177 | "cell_type": "markdown",
178 | "metadata": {
179 | "application/vnd.databricks.v1+cell": {
180 | "inputWidgets": {},
181 | "nuid": "1d1251bd-819c-45a7-8a00-acc09d700967",
182 | "showTitle": false,
183 | "title": ""
184 | }
185 | },
186 | "source": [
187 | "**Merge two dictionaries**"
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": 5,
193 | "metadata": {
194 | "application/vnd.databricks.v1+cell": {
195 | "inputWidgets": {},
196 | "nuid": "31411200-dc8c-43e3-99c9-10c8d1b1dac3",
197 | "showTitle": false,
198 | "title": ""
199 | }
200 | },
201 | "outputs": [
202 | {
203 | "data": {
204 | "text/plain": [
205 | "{'model': 'Jetta', 'year': 2020, 'fuel': 'Solar', 'capacity': 4}"
206 | ]
207 | },
208 | "execution_count": 5,
209 | "metadata": {},
210 | "output_type": "execute_result"
211 | }
212 | ],
213 | "source": [
214 | "D1 = {'model': 'Beetle',\n",
215 | " 'year': 2021,\n",
216 | " 'model': 'Jetta'}\n",
217 | "\n",
218 | "D2 = {'year': 2020,\n",
219 | " 'fuel': 'Solar',\n",
220 | " 'capacity': 4}\n",
221 | "\n",
222 | "D1.update(D2)\n",
223 | "D1"
224 | ]
225 | },
226 | {
227 | "cell_type": "markdown",
228 | "metadata": {
229 | "application/vnd.databricks.v1+cell": {
230 | "inputWidgets": {},
231 | "nuid": "fb08f113-c8cc-445a-b61b-9a6751be4bbd",
232 | "showTitle": false,
233 | "title": ""
234 | }
235 | },
236 | "source": [
237 | "**Remove an Item by Key**\n",
238 | "\n",
239 | "If you know the key of the item you want, you can use pop() method. It removes the key and returns its value."
240 | ]
241 | },
242 | {
243 | "cell_type": "code",
244 | "execution_count": 6,
245 | "metadata": {
246 | "application/vnd.databricks.v1+cell": {
247 | "inputWidgets": {},
248 | "nuid": "99ca58f4-f3b2-48d9-a0ef-4dcfea1c789e",
249 | "showTitle": false,
250 | "title": ""
251 | }
252 | },
253 | "outputs": [
254 | {
255 | "name": "stdout",
256 | "output_type": "stream",
257 | "text": [
258 | "{'model': 'Beetle', 'maker': 'Volkswagon'}\n",
259 | "2021\n"
260 | ]
261 | }
262 | ],
263 | "source": [
264 | "D = {'model': 'Beetle',\n",
265 | " 'year': 2021,\n",
266 | " 'maker': 'Volkswagon'}\n",
267 | "\n",
268 | "x = D.pop('year')\n",
269 | "print(D)\n",
270 | "\n",
271 | "# get removed value\n",
272 | "print(x)"
273 | ]
274 | },
275 | {
276 | "cell_type": "markdown",
277 | "metadata": {
278 | "application/vnd.databricks.v1+cell": {
279 | "inputWidgets": {},
280 | "nuid": "c34868c8-57b5-4500-9a7c-3d488f5c2284",
281 | "showTitle": false,
282 | "title": ""
283 | }
284 | },
285 | "source": [
286 | "Get All Keys, Values and Key:Value Pairs"
287 | ]
288 | },
289 | {
290 | "cell_type": "code",
291 | "execution_count": 7,
292 | "metadata": {
293 | "application/vnd.databricks.v1+cell": {
294 | "inputWidgets": {},
295 | "nuid": "c22c2958-18ae-4feb-86b6-9854f454152a",
296 | "showTitle": false,
297 | "title": ""
298 | }
299 | },
300 | "outputs": [
301 | {
302 | "name": "stdout",
303 | "output_type": "stream",
304 | "text": [
305 | "['model', 'year', 'maker']\n",
306 | "['Beetle', 2021, 'Volkswagon']\n",
307 | "[('model', 'Beetle'), ('year', 2021), ('maker', 'Volkswagon')]\n"
308 | ]
309 | }
310 | ],
311 | "source": [
312 | "D = {'model': 'Beetle',\n",
313 | " 'year': 2021,\n",
314 | " 'maker': 'Volkswagon'}\n",
315 | "\n",
316 | "# get all keys\n",
317 | "print(list(D.keys()))\n",
318 | "\n",
319 | "\n",
320 | "# get all values\n",
321 | "print(list(D.values()))\n",
322 | "\n",
323 | "# get all pairs\n",
324 | "print(list(D.items()))"
325 | ]
326 | },
327 | {
328 | "cell_type": "markdown",
329 | "metadata": {
330 | "application/vnd.databricks.v1+cell": {
331 | "inputWidgets": {},
332 | "nuid": "f3092742-3264-40b8-9ff1-498a835105f3",
333 | "showTitle": false,
334 | "title": ""
335 | }
336 | },
337 | "source": [
338 | "Iterate through a dictionary. If you use a dictionary in a for loop, it traverses the keys of the dictionary by default."
339 | ]
340 | },
341 | {
342 | "cell_type": "code",
343 | "execution_count": 8,
344 | "metadata": {
345 | "application/vnd.databricks.v1+cell": {
346 | "inputWidgets": {},
347 | "nuid": "0bab42c1-a1e7-4500-b1d5-1e5422f7473a",
348 | "showTitle": false,
349 | "title": ""
350 | },
351 | "scrolled": true
352 | },
353 | "outputs": [
354 | {
355 | "name": "stdout",
356 | "output_type": "stream",
357 | "text": [
358 | "model\n",
359 | "year\n",
360 | "maker\n"
361 | ]
362 | }
363 | ],
364 | "source": [
365 | "D = {'model': 'Beetle',\n",
366 | " 'year': 2021,\n",
367 | " 'maker': 'Volkswagon'}\n",
368 | "\n",
369 | "for x in D:\n",
370 | " print(x)"
371 | ]
372 | },
373 | {
374 | "cell_type": "markdown",
375 | "metadata": {
376 | "application/vnd.databricks.v1+cell": {
377 | "inputWidgets": {},
378 | "nuid": "f35a9dad-36ee-457e-970f-695dae7c8a9b",
379 | "showTitle": false,
380 | "title": ""
381 | }
382 | },
383 | "source": [
384 | "To iterate over the values of a dictionary, index from key to value inside the for loop."
385 | ]
386 | },
387 | {
388 | "cell_type": "code",
389 | "execution_count": 9,
390 | "metadata": {
391 | "application/vnd.databricks.v1+cell": {
392 | "inputWidgets": {},
393 | "nuid": "455d333f-4770-4ccc-af44-ac068c34caed",
394 | "showTitle": false,
395 | "title": ""
396 | },
397 | "scrolled": true
398 | },
399 | "outputs": [
400 | {
401 | "name": "stdout",
402 | "output_type": "stream",
403 | "text": [
404 | "Beetle\n",
405 | "2021\n",
406 | "Volkswagon\n"
407 | ]
408 | }
409 | ],
410 | "source": [
411 | "D = {'model': 'Beetle',\n",
412 | " 'year': 2021,\n",
413 | " 'maker': 'Volkswagon'}\n",
414 | "\n",
415 | "for x in D:\n",
416 | " print(D[x])"
417 | ]
418 | },
419 | {
420 | "cell_type": "markdown",
421 | "metadata": {
422 | "application/vnd.databricks.v1+cell": {
423 | "inputWidgets": {},
424 | "nuid": "bf9c85de-dc42-4ed6-9d4e-cd9175200a9b",
425 | "showTitle": false,
426 | "title": ""
427 | }
428 | },
429 | "source": [
430 | "**Python Dictionary Methods**\n",
431 | "\n",
432 | "| Syntax | Description |\n",
433 | "| :------------ | :----------- |\n",
434 | "| `clear()` | Removes all items from the dictionary |\n",
435 | "| `copy()` | Returns a shallow copy of the dictionary |\n",
436 | "| `fromkeys()` | Creates a new dictionary with the specified keys and values |\n",
437 | "| `get()` | Returns the value of the specified key |\n",
438 | "| `items()` | Returns a list of key:value pair |\n",
439 | "| `keys()` | Returns a list of all keys from dictionary |\n",
440 | "| `pop()` | Removes and returns single dictionary item with specified key. |\n",
441 | "| `popitem()` | Removes and returns last inserted key:value pair from the dictionary. |\n",
442 | "| `setdefault()` | Returns the value of the specified key, if present. Else, inserts the key with a specified value. |\n",
443 | "| `update()` | Updates the dictionary with the specified key:value pairs |\n",
444 | "| `values()` | Returns a list of all values from dictionary |"
445 | ]
446 | },
447 | {
448 | "cell_type": "markdown",
449 | "metadata": {
450 | "application/vnd.databricks.v1+cell": {
451 | "inputWidgets": {},
452 | "nuid": "342b65ca-6734-4e64-bdb9-5f9c8230e73b",
453 | "showTitle": false,
454 | "title": ""
455 | }
456 | },
457 | "source": [
458 | "# Comprehension\n",
459 | "\n",
460 | "A comprehension is a compact way of creating a Python data structure from iterators. With comprehensions, you can combine loops and conditional tests with a less verbose syntax."
461 | ]
462 | },
463 | {
464 | "cell_type": "markdown",
465 | "metadata": {
466 | "application/vnd.databricks.v1+cell": {
467 | "inputWidgets": {},
468 | "nuid": "756114c4-269f-4ca7-9b3a-e30afe9641e4",
469 | "showTitle": false,
470 | "title": ""
471 | }
472 | },
473 | "source": [
474 | "**List Comprehension**\n",
475 | "\n",
476 | "Suppose you want to create a list of all integer square numbers from 0 to 4. You could build that list by appending one item at a time to an empty list:"
477 | ]
478 | },
479 | {
480 | "cell_type": "code",
481 | "execution_count": 10,
482 | "metadata": {
483 | "application/vnd.databricks.v1+cell": {
484 | "inputWidgets": {},
485 | "nuid": "fb772592-e08b-45f2-be76-3072d408366d",
486 | "showTitle": false,
487 | "title": ""
488 | }
489 | },
490 | "outputs": [
491 | {
492 | "name": "stdout",
493 | "output_type": "stream",
494 | "text": [
495 | "[0, 1, 4, 9, 16]\n"
496 | ]
497 | }
498 | ],
499 | "source": [
500 | "L = []\n",
501 | "for x in range(5):\n",
502 | " L.append(x**2)\n",
503 | "print(L)"
504 | ]
505 | },
506 | {
507 | "cell_type": "markdown",
508 | "metadata": {
509 | "application/vnd.databricks.v1+cell": {
510 | "inputWidgets": {},
511 | "nuid": "41063713-56a7-4dea-9b33-f956c6842eb5",
512 | "showTitle": false,
513 | "title": ""
514 | }
515 | },
516 | "source": [
517 | "Here both approaches produce the same result. However, a more Pythonic way to build a list is by using a list comprehension.\n",
518 | "\n",
519 | "The general syntax for a list comprehension is:\n",
520 | "\n",
521 | "
\n",
522 | "\n",
523 | "Here’s how a list comprehension would build the above list:"
524 | ]
525 | },
526 | {
527 | "cell_type": "code",
528 | "execution_count": 11,
529 | "metadata": {
530 | "application/vnd.databricks.v1+cell": {
531 | "inputWidgets": {},
532 | "nuid": "072f31fa-073a-41d1-b56c-109a3ff32d07",
533 | "showTitle": false,
534 | "title": ""
535 | }
536 | },
537 | "outputs": [
538 | {
539 | "name": "stdout",
540 | "output_type": "stream",
541 | "text": [
542 | "[0, 1, 4, 9, 16]\n"
543 | ]
544 | }
545 | ],
546 | "source": [
547 | "L = [x**2 for x in range(5)]\n",
548 | "print(L)"
549 | ]
550 | },
551 | {
552 | "cell_type": "code",
553 | "execution_count": 12,
554 | "metadata": {
555 | "application/vnd.databricks.v1+cell": {
556 | "inputWidgets": {},
557 | "nuid": "76ec0597-d6d3-4f1b-8b94-f844e4eb1705",
558 | "showTitle": false,
559 | "title": ""
560 | }
561 | },
562 | "outputs": [
563 | {
564 | "name": "stdout",
565 | "output_type": "stream",
566 | "text": [
567 | "['RRR', 'EEE', 'DDD']\n"
568 | ]
569 | }
570 | ],
571 | "source": [
572 | "L = [x*3 for x in 'RED']\n",
573 | "print(L)"
574 | ]
575 | },
576 | {
577 | "cell_type": "code",
578 | "execution_count": 13,
579 | "metadata": {
580 | "application/vnd.databricks.v1+cell": {
581 | "inputWidgets": {},
582 | "nuid": "dfe09d7d-4248-4622-8319-541760aeb875",
583 | "showTitle": false,
584 | "title": ""
585 | }
586 | },
587 | "outputs": [
588 | {
589 | "data": {
590 | "text/plain": [
591 | "['red', 'green', 'blue']"
592 | ]
593 | },
594 | "execution_count": 13,
595 | "metadata": {},
596 | "output_type": "execute_result"
597 | }
598 | ],
599 | "source": [
600 | "colors = [' red', ' green ', 'blue ']\n",
601 | "L = [color.strip() for color in colors]\n",
602 | "L"
603 | ]
604 | },
605 | {
606 | "cell_type": "code",
607 | "execution_count": 14,
608 | "metadata": {
609 | "application/vnd.databricks.v1+cell": {
610 | "inputWidgets": {},
611 | "nuid": "76d63715-8d89-4ec7-9421-d229b3b3c546",
612 | "showTitle": false,
613 | "title": ""
614 | },
615 | "scrolled": true
616 | },
617 | "outputs": [
618 | {
619 | "name": "stdout",
620 | "output_type": "stream",
621 | "text": [
622 | "[(0, 0), (1, 1), (2, 4), (3, 9)]\n"
623 | ]
624 | }
625 | ],
626 | "source": [
627 | "L = [(x, x**2) for x in range(4)]\n",
628 | "print(L)"
629 | ]
630 | },
631 | {
632 | "cell_type": "markdown",
633 | "metadata": {
634 | "application/vnd.databricks.v1+cell": {
635 | "inputWidgets": {},
636 | "nuid": "3945e9c8-fc53-44c5-995b-3f1dc22874c2",
637 | "showTitle": false,
638 | "title": ""
639 | }
640 | },
641 | "source": [
642 | "**List Comprehension with if Clause**\n",
643 | "\n",
644 | "A list comprehension may have an optional associated if clause to filter items out of the result. Iterable’s items are skipped for which the if clause is not true."
645 | ]
646 | },
647 | {
648 | "cell_type": "code",
649 | "execution_count": 15,
650 | "metadata": {
651 | "application/vnd.databricks.v1+cell": {
652 | "inputWidgets": {},
653 | "nuid": "3a97ba94-4fc4-4500-8839-9ac606095bfd",
654 | "showTitle": false,
655 | "title": ""
656 | }
657 | },
658 | "outputs": [
659 | {
660 | "name": "stdout",
661 | "output_type": "stream",
662 | "text": [
663 | "[0, 2, 4]\n"
664 | ]
665 | }
666 | ],
667 | "source": [
668 | "# Filter list to exclude negative numbers\n",
669 | "vec = [-4, -2, 0, 2, 4]\n",
670 | "L = [x for x in vec if x >= 0]\n",
671 | "print(L)"
672 | ]
673 | },
674 | {
675 | "cell_type": "code",
676 | "execution_count": 16,
677 | "metadata": {
678 | "application/vnd.databricks.v1+cell": {
679 | "inputWidgets": {},
680 | "nuid": "a2cba93a-4832-4311-bad3-d896dde0f47a",
681 | "showTitle": false,
682 | "title": ""
683 | }
684 | },
685 | "outputs": [
686 | {
687 | "name": "stdout",
688 | "output_type": "stream",
689 | "text": [
690 | "[0, 2, 4]\n"
691 | ]
692 | }
693 | ],
694 | "source": [
695 | "# Without list comprehension\n",
696 | "vec = [-4, -2, 0, 2, 4]\n",
697 | "L = []\n",
698 | "for x in vec:\n",
699 | " if x >= 0:\n",
700 | " L.append(x)\n",
701 | "print(L)"
702 | ]
703 | },
704 | {
705 | "cell_type": "markdown",
706 | "metadata": {
707 | "application/vnd.databricks.v1+cell": {
708 | "inputWidgets": {},
709 | "nuid": "51128456-09b3-4175-9387-67f7d6a7c5ed",
710 | "showTitle": false,
711 | "title": ""
712 | }
713 | },
714 | "source": [
715 | "**Nested List Comprehensions**\n",
716 | "\n",
717 | "The initial expression in a list comprehension can be any expression, including another list comprehension.\n",
718 | "\n",
719 | "
"
720 | ]
721 | },
722 | {
723 | "cell_type": "code",
724 | "execution_count": 17,
725 | "metadata": {
726 | "application/vnd.databricks.v1+cell": {
727 | "inputWidgets": {},
728 | "nuid": "94b80a6f-9833-4662-874d-33ecc4bb6112",
729 | "showTitle": false,
730 | "title": ""
731 | }
732 | },
733 | "outputs": [
734 | {
735 | "name": "stdout",
736 | "output_type": "stream",
737 | "text": [
738 | "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
739 | ]
740 | }
741 | ],
742 | "source": [
743 | "# With list comprehension\n",
744 | "vector = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
745 | "L = [number for x in vector for number in x]\n",
746 | "print(L)"
747 | ]
748 | },
749 | {
750 | "cell_type": "code",
751 | "execution_count": 18,
752 | "metadata": {
753 | "application/vnd.databricks.v1+cell": {
754 | "inputWidgets": {},
755 | "nuid": "4e49a38e-2c2b-4585-bc73-b55193b9bfb1",
756 | "showTitle": false,
757 | "title": ""
758 | }
759 | },
760 | "outputs": [
761 | {
762 | "name": "stdout",
763 | "output_type": "stream",
764 | "text": [
765 | "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
766 | ]
767 | }
768 | ],
769 | "source": [
770 | "# Equivalent to the following plain, old nested loop:\n",
771 | "vector = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
772 | "L = []\n",
773 | "for x in vector:\n",
774 | " for number in x:\n",
775 | " L.append(number)\n",
776 | "print(L)"
777 | ]
778 | },
779 | {
780 | "cell_type": "code",
781 | "execution_count": 19,
782 | "metadata": {
783 | "application/vnd.databricks.v1+cell": {
784 | "inputWidgets": {},
785 | "nuid": "b89320a4-c20e-49f0-8d58-d95f9850b72a",
786 | "showTitle": false,
787 | "title": ""
788 | }
789 | },
790 | "outputs": [
791 | {
792 | "data": {
793 | "text/plain": [
794 | "[[1, 4, 7], [2, 5, 8], [3, 6, 9]]"
795 | ]
796 | },
797 | "execution_count": 19,
798 | "metadata": {},
799 | "output_type": "execute_result"
800 | }
801 | ],
802 | "source": [
803 | "matrix = [[1, 2, 3],\n",
804 | " [4, 5, 6],\n",
805 | " [7, 8, 9]]\n",
806 | "L = [[row[i] for row in matrix] for i in range(3)]\n",
807 | "L"
808 | ]
809 | },
810 | {
811 | "cell_type": "markdown",
812 | "metadata": {
813 | "application/vnd.databricks.v1+cell": {
814 | "inputWidgets": {},
815 | "nuid": "479c4974-62bd-49f5-857d-25c905792afe",
816 | "showTitle": false,
817 | "title": ""
818 | }
819 | },
820 | "source": [
821 | "**List Comprehension vs map() + lambda**\n",
822 | "\n",
823 | "When all you’re doing is calling an already-defined function on each element, map(f, L) is a little faster than the corresponding list comprehension [f(x) for x in L]. Following example collects the ASCII codes of all characters in an entire string."
824 | ]
825 | },
826 | {
827 | "cell_type": "code",
828 | "execution_count": 20,
829 | "metadata": {
830 | "application/vnd.databricks.v1+cell": {
831 | "inputWidgets": {},
832 | "nuid": "2fa0b8c0-7331-447c-b514-e9903e3beade",
833 | "showTitle": false,
834 | "title": ""
835 | }
836 | },
837 | "outputs": [
838 | {
839 | "name": "stdout",
840 | "output_type": "stream",
841 | "text": [
842 | "[102, 111, 111]\n",
843 | "[102, 111, 111]\n"
844 | ]
845 | }
846 | ],
847 | "source": [
848 | "# With list comprehension\n",
849 | "L = [ord(x) for x in 'foo']\n",
850 | "print(L)\n",
851 | "\n",
852 | "# With map() function\n",
853 | "list(map(ord, 'foo'))\n",
854 | "print(L)"
855 | ]
856 | },
857 | {
858 | "cell_type": "markdown",
859 | "metadata": {
860 | "application/vnd.databricks.v1+cell": {
861 | "inputWidgets": {},
862 | "nuid": "6b7f08cd-d1ca-4b8d-9279-cbea081034b6",
863 | "showTitle": false,
864 | "title": ""
865 | }
866 | },
867 | "source": [
868 | "What is `lambda` in python?\n",
869 | "\n",
870 | "A lambda function is a small anonymous function.It can take any number of arguments, but can only have one expression."
871 | ]
872 | },
873 | {
874 | "cell_type": "code",
875 | "execution_count": 21,
876 | "metadata": {
877 | "application/vnd.databricks.v1+cell": {
878 | "inputWidgets": {},
879 | "nuid": "19f4a275-de92-4b9f-87e9-72321dbe3cf9",
880 | "showTitle": false,
881 | "title": ""
882 | }
883 | },
884 | "outputs": [
885 | {
886 | "name": "stdout",
887 | "output_type": "stream",
888 | "text": [
889 | "15\n"
890 | ]
891 | }
892 | ],
893 | "source": [
894 | "x = lambda a : a + 10\n",
895 | "print(x(5))"
896 | ]
897 | },
898 | {
899 | "cell_type": "code",
900 | "execution_count": 22,
901 | "metadata": {
902 | "application/vnd.databricks.v1+cell": {
903 | "inputWidgets": {},
904 | "nuid": "f36bb781-9f5d-4198-b3f0-ebdc31692589",
905 | "showTitle": false,
906 | "title": ""
907 | }
908 | },
909 | "outputs": [
910 | {
911 | "name": "stdout",
912 | "output_type": "stream",
913 | "text": [
914 | "30\n"
915 | ]
916 | }
917 | ],
918 | "source": [
919 | "x = lambda a, b : a * b\n",
920 | "print(x(5, 6))"
921 | ]
922 | },
923 | {
924 | "cell_type": "markdown",
925 | "metadata": {
926 | "application/vnd.databricks.v1+cell": {
927 | "inputWidgets": {},
928 | "nuid": "f61b13fc-d0c0-4a8e-92ed-92a41ec5e1a6",
929 | "showTitle": false,
930 | "title": ""
931 | }
932 | },
933 | "source": [
934 | "However, when evaluating any other expression, `[some_expr for x in L]` is faster and clearer than `map(lambda x: some_expr, L)`, because the map incurs an extra function call for each element. Following example creates a list of all integer square numbers."
935 | ]
936 | },
937 | {
938 | "cell_type": "code",
939 | "execution_count": 23,
940 | "metadata": {
941 | "application/vnd.databricks.v1+cell": {
942 | "inputWidgets": {},
943 | "nuid": "28dc1540-0d43-4a2d-b7e4-86023ad53f4a",
944 | "showTitle": false,
945 | "title": ""
946 | }
947 | },
948 | "outputs": [
949 | {
950 | "name": "stdout",
951 | "output_type": "stream",
952 | "text": [
953 | "[0, 2, 4, 6, 8]\n",
954 | "[0, 2, 4, 6, 8]\n"
955 | ]
956 | }
957 | ],
958 | "source": [
959 | "L = [x for x in range(10) if x % 2 == 0]\n",
960 | "print(L)\n",
961 | "\n",
962 | "# With filter() function\n",
963 | "L = list(filter((lambda x: x % 2 == 0), range(10)))\n",
964 | "print(L)"
965 | ]
966 | },
967 | {
968 | "cell_type": "markdown",
969 | "metadata": {
970 | "application/vnd.databricks.v1+cell": {
971 | "inputWidgets": {},
972 | "nuid": "9a4c9ce8-d732-4eb2-bc98-f58a9b212653",
973 | "showTitle": false,
974 | "title": ""
975 | }
976 | },
977 | "source": [
978 | "**Dictionary Comprehension**\n",
979 | "\n",
980 | "The idea of comprehension is not just unique to lists in Python. Dictionaries also have comprehensions."
981 | ]
982 | },
983 | {
984 | "cell_type": "code",
985 | "execution_count": 24,
986 | "metadata": {
987 | "application/vnd.databricks.v1+cell": {
988 | "inputWidgets": {},
989 | "nuid": "ad3c82f7-37c4-44c4-b20d-ba0b5f766198",
990 | "showTitle": false,
991 | "title": ""
992 | }
993 | },
994 | "outputs": [
995 | {
996 | "name": "stdout",
997 | "output_type": "stream",
998 | "text": [
999 | "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n"
1000 | ]
1001 | }
1002 | ],
1003 | "source": [
1004 | "D = {}\n",
1005 | "for x in range(5):\n",
1006 | " D[x] = x**2\n",
1007 | "\n",
1008 | "print(D)"
1009 | ]
1010 | },
1011 | {
1012 | "cell_type": "markdown",
1013 | "metadata": {
1014 | "application/vnd.databricks.v1+cell": {
1015 | "inputWidgets": {},
1016 | "nuid": "2a1f800e-9265-4dc7-b26d-385ec8b0a5fd",
1017 | "showTitle": false,
1018 | "title": ""
1019 | }
1020 | },
1021 | "source": [
1022 | "The general syntax for a dictionary comprehension is:\n",
1023 | "\n",
1024 | "
"
1025 | ]
1026 | },
1027 | {
1028 | "cell_type": "code",
1029 | "execution_count": 25,
1030 | "metadata": {
1031 | "application/vnd.databricks.v1+cell": {
1032 | "inputWidgets": {},
1033 | "nuid": "518d439d-fc15-4f63-9662-6466dd86b613",
1034 | "showTitle": false,
1035 | "title": ""
1036 | }
1037 | },
1038 | "outputs": [
1039 | {
1040 | "name": "stdout",
1041 | "output_type": "stream",
1042 | "text": [
1043 | "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n"
1044 | ]
1045 | }
1046 | ],
1047 | "source": [
1048 | "D = {x: x**2 for x in range(5)}\n",
1049 | "print(D)"
1050 | ]
1051 | },
1052 | {
1053 | "cell_type": "code",
1054 | "execution_count": 26,
1055 | "metadata": {
1056 | "application/vnd.databricks.v1+cell": {
1057 | "inputWidgets": {},
1058 | "nuid": "4f1efee4-e709-454f-a1ec-a8540c621bc5",
1059 | "showTitle": false,
1060 | "title": ""
1061 | }
1062 | },
1063 | "outputs": [
1064 | {
1065 | "name": "stdout",
1066 | "output_type": "stream",
1067 | "text": [
1068 | "{'red': 'RED', 'green': 'GREEN', 'blue': 'BLUE'}\n"
1069 | ]
1070 | }
1071 | ],
1072 | "source": [
1073 | "L = ['ReD', 'GrEeN', 'BlUe']\n",
1074 | "D = {c.lower(): c.upper() for c in L}\n",
1075 | "print(D)"
1076 | ]
1077 | }
1078 | ],
1079 | "metadata": {
1080 | "anaconda-cloud": {},
1081 | "application/vnd.databricks.v1+notebook": {
1082 | "dashboards": [],
1083 | "language": "python",
1084 | "notebookMetadata": {
1085 | "pythonIndentUnit": 2
1086 | },
1087 | "notebookName": "Python_Part2",
1088 | "notebookOrigID": 2425280650113424,
1089 | "widgets": {}
1090 | },
1091 | "kernelspec": {
1092 | "display_name": "Python 3",
1093 | "language": "python",
1094 | "name": "python3"
1095 | },
1096 | "language_info": {
1097 | "codemirror_mode": {
1098 | "name": "ipython",
1099 | "version": 3
1100 | },
1101 | "file_extension": ".py",
1102 | "mimetype": "text/x-python",
1103 | "name": "python",
1104 | "nbconvert_exporter": "python",
1105 | "pygments_lexer": "ipython3",
1106 | "version": "3.7.3"
1107 | }
1108 | },
1109 | "nbformat": 4,
1110 | "nbformat_minor": 1
1111 | }
1112 |
--------------------------------------------------------------------------------
/Python/.ipynb_checkpoints/Python_Part5-checkpoint.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Python for Data Science and Machine Learning - Part 5\n",
8 | "--------"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "metadata": {
14 | "application/vnd.databricks.v1+cell": {
15 | "inputWidgets": {},
16 | "nuid": "ecfe6b18-e725-4a6f-b475-4d78be5faa74",
17 | "showTitle": false,
18 | "title": ""
19 | }
20 | },
21 | "source": [
22 | "## Functions\n",
23 | "\n",
24 | "A function is a relationship or mapping between one or more inputs and a set of outputs. Mathematically, a function is generally represented as follows:\n",
25 | "\n",
26 | "
\n",
27 | "\n",
28 | "where f is a function that operates on the inputs x and y and generates z as an output. In programming, a function is a self-contained block of code that encapsulates a specific task or related group of tasks. The functions allow us to define a reusable block of code that can be used repeatedly in a program.\n",
29 | "\n",
30 | "Python provides several built-in functions such as print(), len() and type(), but we can also define our own functions to use within our programs."
31 | ]
32 | },
33 | {
34 | "cell_type": "markdown",
35 | "metadata": {
36 | "application/vnd.databricks.v1+cell": {
37 | "inputWidgets": {},
38 | "nuid": "cd7ac8e4-73aa-44cf-acdb-1d21599d5c75",
39 | "showTitle": false,
40 | "title": ""
41 | }
42 | },
43 | "source": [
44 | "**Syntax**\n",
45 | "\n",
46 | "The basic syntax for a Python function definition is:\n",
47 | "\n",
48 | "
"
49 | ]
50 | },
51 | {
52 | "cell_type": "markdown",
53 | "metadata": {
54 | "application/vnd.databricks.v1+cell": {
55 | "inputWidgets": {},
56 | "nuid": "a029be1e-96d1-44b8-9358-1d91e01d33ff",
57 | "showTitle": false,
58 | "title": ""
59 | }
60 | },
61 | "source": [
62 | "**Create a function**\n",
63 | "\n",
64 | "A function is defined using the `def` keyword."
65 | ]
66 | },
67 | {
68 | "cell_type": "code",
69 | "execution_count": 1,
70 | "metadata": {
71 | "application/vnd.databricks.v1+cell": {
72 | "inputWidgets": {},
73 | "nuid": "8e9f77ee-46cd-4c1d-b216-75b1a5824ec5",
74 | "showTitle": false,
75 | "title": ""
76 | }
77 | },
78 | "outputs": [],
79 | "source": [
80 | "def hello():\n",
81 | " print(\"Hello World!\")"
82 | ]
83 | },
84 | {
85 | "cell_type": "markdown",
86 | "metadata": {
87 | "application/vnd.databricks.v1+cell": {
88 | "inputWidgets": {},
89 | "nuid": "da5c6e8f-1a8b-457f-89fb-880a9b895068",
90 | "showTitle": false,
91 | "title": ""
92 | }
93 | },
94 | "source": [
95 | "**Call a function**"
96 | ]
97 | },
98 | {
99 | "cell_type": "code",
100 | "execution_count": 2,
101 | "metadata": {
102 | "application/vnd.databricks.v1+cell": {
103 | "inputWidgets": {},
104 | "nuid": "677125a6-a39b-4cc8-97a4-15c57f09b2a7",
105 | "showTitle": false,
106 | "title": ""
107 | }
108 | },
109 | "outputs": [
110 | {
111 | "name": "stdout",
112 | "output_type": "stream",
113 | "text": [
114 | "Hello World!\n"
115 | ]
116 | }
117 | ],
118 | "source": [
119 | "hello()"
120 | ]
121 | },
122 | {
123 | "cell_type": "markdown",
124 | "metadata": {
125 | "application/vnd.databricks.v1+cell": {
126 | "inputWidgets": {},
127 | "nuid": "b7943bb3-7623-4d93-932e-c5ec1ac0dcfb",
128 | "showTitle": false,
129 | "title": ""
130 | }
131 | },
132 | "source": [
133 | "**Pass Arguments**\n",
134 | "\n",
135 | "We can pass values, known as arguments, to a function that are declared after the function name in parentheses."
136 | ]
137 | },
138 | {
139 | "cell_type": "code",
140 | "execution_count": 3,
141 | "metadata": {
142 | "application/vnd.databricks.v1+cell": {
143 | "inputWidgets": {},
144 | "nuid": "5372c866-82e0-4494-8f11-44c3d2883894",
145 | "showTitle": false,
146 | "title": ""
147 | }
148 | },
149 | "outputs": [],
150 | "source": [
151 | "# pass a single argument\n",
152 | "def hello(name):\n",
153 | " print('Hello,', name)\n",
154 | " \n",
155 | "# pass mutiple arguments\n",
156 | "\n",
157 | "def func(country,city):\n",
158 | " print(f'{city} is the capital of {country}')"
159 | ]
160 | },
161 | {
162 | "cell_type": "code",
163 | "execution_count": 4,
164 | "metadata": {
165 | "application/vnd.databricks.v1+cell": {
166 | "inputWidgets": {},
167 | "nuid": "0052e5f6-ebe7-438f-9cd4-8dd40c5b271b",
168 | "showTitle": false,
169 | "title": ""
170 | }
171 | },
172 | "outputs": [
173 | {
174 | "name": "stdout",
175 | "output_type": "stream",
176 | "text": [
177 | "Hello, Messi\n",
178 | "Paris is the capital of France\n"
179 | ]
180 | }
181 | ],
182 | "source": [
183 | "hello('Messi')\n",
184 | "func('France','Paris')"
185 | ]
186 | },
187 | {
188 | "cell_type": "markdown",
189 | "metadata": {
190 | "application/vnd.databricks.v1+cell": {
191 | "inputWidgets": {},
192 | "nuid": "73db98cf-97bc-4162-933c-9b1ab6cfd3b4",
193 | "showTitle": false,
194 | "title": ""
195 | }
196 | },
197 | "source": [
198 | "**Type of Arguments**\n",
199 | "\n",
200 | "1. Positional Arguments\n",
201 | "2. Keyword Arguments\n",
202 | "3. Default Arguments\n",
203 | "4. Variable Length Positional Arguments (*args)\n",
204 | "5. Variable Length Keyword Arguments (**kwargs)"
205 | ]
206 | },
207 | {
208 | "cell_type": "markdown",
209 | "metadata": {
210 | "application/vnd.databricks.v1+cell": {
211 | "inputWidgets": {},
212 | "nuid": "3f3e25cb-8284-4691-a223-2fe88ef592e5",
213 | "showTitle": false,
214 | "title": ""
215 | }
216 | },
217 | "source": [
218 | "Positional arguments - The positional argumentsare passed to the respective parameters in order."
219 | ]
220 | },
221 | {
222 | "cell_type": "code",
223 | "execution_count": 5,
224 | "metadata": {
225 | "application/vnd.databricks.v1+cell": {
226 | "inputWidgets": {},
227 | "nuid": "4f06a2ad-ad62-4b5e-944d-92b780f21fc9",
228 | "showTitle": false,
229 | "title": ""
230 | }
231 | },
232 | "outputs": [
233 | {
234 | "name": "stdout",
235 | "output_type": "stream",
236 | "text": [
237 | "Paris is the capital of France\n"
238 | ]
239 | }
240 | ],
241 | "source": [
242 | "# positional arguments\n",
243 | "def func(country,city):\n",
244 | " print(f'{city} is the capital of {country}')\n",
245 | " \n",
246 | "func('France','Paris')"
247 | ]
248 | },
249 | {
250 | "cell_type": "markdown",
251 | "metadata": {
252 | "application/vnd.databricks.v1+cell": {
253 | "inputWidgets": {},
254 | "nuid": "44dcb712-ba20-476c-b353-995da0004c2e",
255 | "showTitle": false,
256 | "title": ""
257 | }
258 | },
259 | "source": [
260 | "Keyword arguments - Pass arguments using the names of their corresponding parameters"
261 | ]
262 | },
263 | {
264 | "cell_type": "code",
265 | "execution_count": 6,
266 | "metadata": {
267 | "application/vnd.databricks.v1+cell": {
268 | "inputWidgets": {},
269 | "nuid": "53238ce6-1317-4f4d-b0c9-0ff15196a4d7",
270 | "showTitle": false,
271 | "title": ""
272 | }
273 | },
274 | "outputs": [
275 | {
276 | "name": "stdout",
277 | "output_type": "stream",
278 | "text": [
279 | "Paris is the capital of France\n"
280 | ]
281 | }
282 | ],
283 | "source": [
284 | "# keyword arguments can be put in any order\n",
285 | "def func(country,city):\n",
286 | " print(f'{city} is the capital of {country}')\n",
287 | "\n",
288 | "func(city='Paris',country='France')"
289 | ]
290 | },
291 | {
292 | "cell_type": "markdown",
293 | "metadata": {
294 | "application/vnd.databricks.v1+cell": {
295 | "inputWidgets": {},
296 | "nuid": "b0946438-9ce1-41ac-bee9-2cec5dbd8bd9",
297 | "showTitle": false,
298 | "title": ""
299 | }
300 | },
301 | "source": [
302 | "Default arguments - The default value is used when the no argument is passed durina a function call"
303 | ]
304 | },
305 | {
306 | "cell_type": "code",
307 | "execution_count": 7,
308 | "metadata": {
309 | "application/vnd.databricks.v1+cell": {
310 | "inputWidgets": {},
311 | "nuid": "6074fe1a-221b-482e-85d8-b9a56f5eabf0",
312 | "showTitle": false,
313 | "title": ""
314 | }
315 | },
316 | "outputs": [
317 | {
318 | "name": "stdout",
319 | "output_type": "stream",
320 | "text": [
321 | "Paris is the capital of France\n"
322 | ]
323 | }
324 | ],
325 | "source": [
326 | "def func(country,city = 'Paris'):\n",
327 | " print(f'{city} is the capital of {country}')\n",
328 | " \n",
329 | "func('France')"
330 | ]
331 | },
332 | {
333 | "cell_type": "markdown",
334 | "metadata": {
335 | "application/vnd.databricks.v1+cell": {
336 | "inputWidgets": {},
337 | "nuid": "e5d8309a-2b9d-4eb6-8553-89e6faf6b10f",
338 | "showTitle": false,
339 | "title": ""
340 | }
341 | },
342 | "source": [
343 | "Note: The default argument should be preceeded by non-default arguments"
344 | ]
345 | },
346 | {
347 | "cell_type": "markdown",
348 | "metadata": {
349 | "application/vnd.databricks.v1+cell": {
350 | "inputWidgets": {},
351 | "nuid": "ca65a173-3716-4fe5-a086-5aa7f610018f",
352 | "showTitle": false,
353 | "title": ""
354 | }
355 | },
356 | "source": [
357 | "Variable length arguments - Pass variable number of arguments to a function using special symbols\n",
358 | "\n",
359 | "- *args - arugments\n",
360 | "- **kwargs - keyword arguments"
361 | ]
362 | },
363 | {
364 | "cell_type": "code",
365 | "execution_count": 8,
366 | "metadata": {
367 | "application/vnd.databricks.v1+cell": {
368 | "inputWidgets": {},
369 | "nuid": "ea83fe74-3f93-4c68-86f9-d249c0ff9765",
370 | "showTitle": false,
371 | "title": ""
372 | }
373 | },
374 | "outputs": [
375 | {
376 | "name": "stdout",
377 | "output_type": "stream",
378 | "text": [
379 | "6\n"
380 | ]
381 | }
382 | ],
383 | "source": [
384 | "# sum integers using *args\n",
385 | "def my_sum(*args):\n",
386 | " result = 0\n",
387 | " # Iterating over the Python args tuple\n",
388 | " for x in args:\n",
389 | " result += x\n",
390 | " return result\n",
391 | "\n",
392 | "print(my_sum(1, 2, 3))"
393 | ]
394 | },
395 | {
396 | "cell_type": "code",
397 | "execution_count": 9,
398 | "metadata": {
399 | "application/vnd.databricks.v1+cell": {
400 | "inputWidgets": {},
401 | "nuid": "975d9247-ade6-4a38-a12e-0d9af8a33712",
402 | "showTitle": false,
403 | "title": ""
404 | }
405 | },
406 | "outputs": [
407 | {
408 | "name": "stdout",
409 | "output_type": "stream",
410 | "text": [
411 | "RealPythonIsGreat!\n"
412 | ]
413 | }
414 | ],
415 | "source": [
416 | "# concatenate strings using **kwargs\n",
417 | "def concatenate(**kwargs):\n",
418 | " result = \"\"\n",
419 | " # Iterating over the Python kwargs dictionary\n",
420 | " for arg in kwargs.values():\n",
421 | " result += arg\n",
422 | " return result\n",
423 | "\n",
424 | "print(concatenate(a=\"Real\", b=\"Python\", c=\"Is\", d=\"Great\", e=\"!\"))"
425 | ]
426 | },
427 | {
428 | "cell_type": "markdown",
429 | "metadata": {
430 | "application/vnd.databricks.v1+cell": {
431 | "inputWidgets": {},
432 | "nuid": "1eb92d78-6c22-4231-b232-f624ca0e1784",
433 | "showTitle": false,
434 | "title": ""
435 | }
436 | },
437 | "source": [
438 | "**Return value(s)**"
439 | ]
440 | },
441 | {
442 | "cell_type": "code",
443 | "execution_count": 10,
444 | "metadata": {
445 | "application/vnd.databricks.v1+cell": {
446 | "inputWidgets": {},
447 | "nuid": "c81aaf39-1662-43a0-aa37-cb411cdd934a",
448 | "showTitle": false,
449 | "title": ""
450 | }
451 | },
452 | "outputs": [
453 | {
454 | "data": {
455 | "text/plain": [
456 | "5"
457 | ]
458 | },
459 | "execution_count": 10,
460 | "metadata": {},
461 | "output_type": "execute_result"
462 | }
463 | ],
464 | "source": [
465 | "# return a single value\n",
466 | "def my_sum(a,b):\n",
467 | " return a+b\n",
468 | "my_sum(2,3)"
469 | ]
470 | },
471 | {
472 | "cell_type": "code",
473 | "execution_count": 11,
474 | "metadata": {
475 | "application/vnd.databricks.v1+cell": {
476 | "inputWidgets": {},
477 | "nuid": "c06e18dc-17e7-40f7-a5e9-96598d0ca75e",
478 | "showTitle": false,
479 | "title": ""
480 | }
481 | },
482 | "outputs": [
483 | {
484 | "data": {
485 | "text/plain": [
486 | "(5, 1)"
487 | ]
488 | },
489 | "execution_count": 11,
490 | "metadata": {},
491 | "output_type": "execute_result"
492 | }
493 | ],
494 | "source": [
495 | "# return multiple values\n",
496 | "\n",
497 | "def sum_diff(a,b):\n",
498 | " return a+b, a-b\n",
499 | "\n",
500 | "sum_diff(3,2)"
501 | ]
502 | },
503 | {
504 | "cell_type": "markdown",
505 | "metadata": {
506 | "application/vnd.databricks.v1+cell": {
507 | "inputWidgets": {},
508 | "nuid": "9d80eae8-4d80-424b-bb0f-c777c94fe560",
509 | "showTitle": false,
510 | "title": ""
511 | }
512 | },
513 | "source": [
514 | "**Docstring**\n",
515 | "\n",
516 | "Attach a documentation to a function definition by including a string right after the function header."
517 | ]
518 | },
519 | {
520 | "cell_type": "code",
521 | "execution_count": 12,
522 | "metadata": {
523 | "application/vnd.databricks.v1+cell": {
524 | "inputWidgets": {},
525 | "nuid": "7ffb5b20-96a3-4ab8-873a-1da7a9dd3533",
526 | "showTitle": false,
527 | "title": ""
528 | }
529 | },
530 | "outputs": [
531 | {
532 | "name": "stdout",
533 | "output_type": "stream",
534 | "text": [
535 | "Help on function hello in module __main__:\n",
536 | "\n",
537 | "hello()\n",
538 | " This function prints\n",
539 | " message on the screen\n",
540 | "\n",
541 | "This function prints\n",
542 | " message on the screen\n"
543 | ]
544 | }
545 | ],
546 | "source": [
547 | "def hello():\n",
548 | " \"\"\"This function prints\n",
549 | " message on the screen\"\"\" \n",
550 | " print('Hello, World!')\n",
551 | " \n",
552 | "help(hello)\n",
553 | "\n",
554 | "# print docstring\n",
555 | "print(hello.__doc__)"
556 | ]
557 | },
558 | {
559 | "cell_type": "markdown",
560 | "metadata": {
561 | "application/vnd.databricks.v1+cell": {
562 | "inputWidgets": {},
563 | "nuid": "2e7e7b4f-968e-4350-be87-12af7697b482",
564 | "showTitle": false,
565 | "title": ""
566 | }
567 | },
568 | "source": [
569 | "## Python Variables Scope\n",
570 | "\n",
571 | "The part of the program where the variable is accessible is called its “scope” and is determined by where the variable is declared. There are four variable scopes in python: local, enclosing, global and built-in scope."
572 | ]
573 | },
574 | {
575 | "cell_type": "markdown",
576 | "metadata": {
577 | "application/vnd.databricks.v1+cell": {
578 | "inputWidgets": {},
579 | "nuid": "a22fe445-bec3-4fcd-828b-1bed961ebbd5",
580 | "showTitle": false,
581 | "title": ""
582 | }
583 | },
584 | "source": [
585 | "**Local Scope**\n",
586 | "\n",
587 | "A variable that is declared within a function has a local scope and is accessible from the point where it is declared and until the end of the function."
588 | ]
589 | },
590 | {
591 | "cell_type": "code",
592 | "execution_count": 13,
593 | "metadata": {
594 | "application/vnd.databricks.v1+cell": {
595 | "inputWidgets": {},
596 | "nuid": "a609a817-c90a-4cb4-bba1-9725ee4afea3",
597 | "showTitle": false,
598 | "title": ""
599 | }
600 | },
601 | "outputs": [
602 | {
603 | "name": "stdout",
604 | "output_type": "stream",
605 | "text": [
606 | "Hello\n"
607 | ]
608 | }
609 | ],
610 | "source": [
611 | "def myfunc():\n",
612 | " x='Hello'\n",
613 | " print (x)\n",
614 | " \n",
615 | "myfunc()\n",
616 | "# print(x)\n",
617 | "# NameError: name 'x' is not defined"
618 | ]
619 | },
620 | {
621 | "cell_type": "markdown",
622 | "metadata": {
623 | "application/vnd.databricks.v1+cell": {
624 | "inputWidgets": {},
625 | "nuid": "7cddf61b-a646-4142-9e89-578abc4bc4e8",
626 | "showTitle": false,
627 | "title": ""
628 | }
629 | },
630 | "source": [
631 | "**Global Scope**"
632 | ]
633 | },
634 | {
635 | "cell_type": "code",
636 | "execution_count": 14,
637 | "metadata": {
638 | "application/vnd.databricks.v1+cell": {
639 | "inputWidgets": {},
640 | "nuid": "5ac67ade-0e14-451a-960b-3279e998e17b",
641 | "showTitle": false,
642 | "title": ""
643 | }
644 | },
645 | "outputs": [
646 | {
647 | "name": "stdout",
648 | "output_type": "stream",
649 | "text": [
650 | "Hello\n",
651 | "Hello\n"
652 | ]
653 | }
654 | ],
655 | "source": [
656 | "x = 'Hello'\n",
657 | "def myfunc():\n",
658 | " print(x)\n",
659 | "myfunc()\n",
660 | "print(x)"
661 | ]
662 | },
663 | {
664 | "cell_type": "markdown",
665 | "metadata": {
666 | "application/vnd.databricks.v1+cell": {
667 | "inputWidgets": {},
668 | "nuid": "ff3e3bd6-93aa-43be-b6c7-4524bb8eeebe",
669 | "showTitle": false,
670 | "title": ""
671 | }
672 | },
673 | "source": [
674 | "**Enclosing Scope**"
675 | ]
676 | },
677 | {
678 | "cell_type": "markdown",
679 | "metadata": {
680 | "application/vnd.databricks.v1+cell": {
681 | "inputWidgets": {},
682 | "nuid": "d7292ed5-b84c-47d2-a087-843912c1fa71",
683 | "showTitle": false,
684 | "title": ""
685 | }
686 | },
687 | "source": [
688 | "From inside, the `inner_func()`, the scope lies between a local and global scope and known as enclosing scope. Here, the value of existing variable x didn’t change because python created a new local variable named x that shadows the variable in the outer scope."
689 | ]
690 | },
691 | {
692 | "cell_type": "code",
693 | "execution_count": 15,
694 | "metadata": {
695 | "application/vnd.databricks.v1+cell": {
696 | "inputWidgets": {},
697 | "nuid": "bdeae6c6-aacf-4cfd-aae7-ea8abd25460d",
698 | "showTitle": false,
699 | "title": ""
700 | }
701 | },
702 | "outputs": [
703 | {
704 | "name": "stdout",
705 | "output_type": "stream",
706 | "text": [
707 | "0\n",
708 | "10\n"
709 | ]
710 | }
711 | ],
712 | "source": [
713 | "def outer_func():\n",
714 | " var = 10\n",
715 | " # nested function\n",
716 | " def inner_func():\n",
717 | " var = 0\n",
718 | " print(var) # x is 0\n",
719 | " inner_func()\n",
720 | " print(var) # x is still 10\n",
721 | "\n",
722 | "outer_func()"
723 | ]
724 | },
725 | {
726 | "cell_type": "markdown",
727 | "metadata": {
728 | "application/vnd.databricks.v1+cell": {
729 | "inputWidgets": {},
730 | "nuid": "223661d1-53eb-4c5d-8316-ff23d8e54a9a",
731 | "showTitle": false,
732 | "title": ""
733 | }
734 | },
735 | "source": [
736 | "By using `nonlocal` keyword, the x inside the nested function now refers to the x outside the function, so changing x inside the function changes the x outside it."
737 | ]
738 | },
739 | {
740 | "cell_type": "code",
741 | "execution_count": 16,
742 | "metadata": {
743 | "application/vnd.databricks.v1+cell": {
744 | "inputWidgets": {},
745 | "nuid": "6857b857-13b0-444c-a26f-7da82c768561",
746 | "showTitle": false,
747 | "title": ""
748 | }
749 | },
750 | "outputs": [
751 | {
752 | "name": "stdout",
753 | "output_type": "stream",
754 | "text": [
755 | "0\n",
756 | "0\n"
757 | ]
758 | }
759 | ],
760 | "source": [
761 | "# enclosing function\n",
762 | "def f1():\n",
763 | " x = 42\n",
764 | " # nested function\n",
765 | " def f2():\n",
766 | " nonlocal x\n",
767 | " x = 0\n",
768 | " print(x) # x is now 0\n",
769 | " f2()\n",
770 | " print(x) # x remains 0\n",
771 | " \n",
772 | "f1()"
773 | ]
774 | },
775 | {
776 | "cell_type": "markdown",
777 | "metadata": {
778 | "application/vnd.databricks.v1+cell": {
779 | "inputWidgets": {},
780 | "nuid": "58fdbb0d-8444-487a-aefe-04ebde20002f",
781 | "showTitle": false,
782 | "title": ""
783 | }
784 | },
785 | "source": [
786 | "**Scoping LEGB Rule**\n",
787 | "\n",
788 | "
\n",
789 | "\n",
790 | "When a variable is referenced, Python follows LEGB rule and searches up to four scopes in this order:\n",
791 | "\n",
792 | "1. first in the local (L) scope,\n",
793 | "\n",
794 | "2. then in the local scopes of any enclosing (E) functions and lambdas,\n",
795 | "\n",
796 | "3. then in the global (G) scope,\n",
797 | "\n",
798 | "4. and finally in then the built-in (B) scope"
799 | ]
800 | },
801 | {
802 | "cell_type": "markdown",
803 | "metadata": {
804 | "application/vnd.databricks.v1+cell": {
805 | "inputWidgets": {},
806 | "nuid": "ba685c45-b733-4b20-8dfb-290c941df96b",
807 | "showTitle": false,
808 | "title": ""
809 | }
810 | },
811 | "source": [
812 | "## Lambda Function\n",
813 | "\n",
814 | "A lambda function is an anonymous function created using the keyword `lambda`"
815 | ]
816 | },
817 | {
818 | "cell_type": "code",
819 | "execution_count": 17,
820 | "metadata": {
821 | "application/vnd.databricks.v1+cell": {
822 | "inputWidgets": {},
823 | "nuid": "1d150e8f-1ca8-46d4-8842-894f5414350d",
824 | "showTitle": false,
825 | "title": ""
826 | }
827 | },
828 | "outputs": [
829 | {
830 | "data": {
831 | "text/plain": [
832 | "4"
833 | ]
834 | },
835 | "execution_count": 17,
836 | "metadata": {},
837 | "output_type": "execute_result"
838 | }
839 | ],
840 | "source": [
841 | "double = lambda x:x**2\n",
842 | "double(2)"
843 | ]
844 | },
845 | {
846 | "cell_type": "code",
847 | "execution_count": 18,
848 | "metadata": {
849 | "application/vnd.databricks.v1+cell": {
850 | "inputWidgets": {},
851 | "nuid": "a402efdb-df29-4291-bd29-8eab53ef4abe",
852 | "showTitle": false,
853 | "title": ""
854 | }
855 | },
856 | "outputs": [
857 | {
858 | "data": {
859 | "text/plain": [
860 | "5"
861 | ]
862 | },
863 | "execution_count": 18,
864 | "metadata": {},
865 | "output_type": "execute_result"
866 | }
867 | ],
868 | "source": [
869 | "add = lambda x, y: x + y\n",
870 | "add(2,3)"
871 | ]
872 | },
873 | {
874 | "cell_type": "code",
875 | "execution_count": 19,
876 | "metadata": {
877 | "application/vnd.databricks.v1+cell": {
878 | "inputWidgets": {},
879 | "nuid": "f97bbb34-6a1d-475f-9030-ee79d0c5826c",
880 | "showTitle": false,
881 | "title": ""
882 | }
883 | },
884 | "outputs": [
885 | {
886 | "data": {
887 | "text/plain": [
888 | "1"
889 | ]
890 | },
891 | "execution_count": 19,
892 | "metadata": {},
893 | "output_type": "execute_result"
894 | }
895 | ],
896 | "source": [
897 | "my_list =[2,1,4]\n",
898 | "# returns the first element of the above list\n",
899 | "b = lambda x:x[1]\n",
900 | "b(my_list)"
901 | ]
902 | },
903 | {
904 | "cell_type": "markdown",
905 | "metadata": {
906 | "application/vnd.databricks.v1+cell": {
907 | "inputWidgets": {},
908 | "nuid": "3b5200f8-784d-4af4-a59b-f88d68dc13ca",
909 | "showTitle": false,
910 | "title": ""
911 | }
912 | },
913 | "source": [
914 | "**Lambdas with map, filter and reduce**"
915 | ]
916 | },
917 | {
918 | "cell_type": "markdown",
919 | "metadata": {
920 | "application/vnd.databricks.v1+cell": {
921 | "inputWidgets": {},
922 | "nuid": "d380304a-ad9f-4ce6-818a-ab012604e0a3",
923 | "showTitle": false,
924 | "title": ""
925 | }
926 | },
927 | "source": [
928 | "`map()` takes a function as a first argument and applies it to each of the elements of its second argument, an iterable (most commonly a list)."
929 | ]
930 | },
931 | {
932 | "cell_type": "code",
933 | "execution_count": 20,
934 | "metadata": {
935 | "application/vnd.databricks.v1+cell": {
936 | "inputWidgets": {},
937 | "nuid": "c98ddf3b-bdcf-4f2a-bcb2-e7aeb3a12369",
938 | "showTitle": false,
939 | "title": ""
940 | }
941 | },
942 | "outputs": [
943 | {
944 | "data": {
945 | "text/plain": [
946 | "[0, 2, 4]"
947 | ]
948 | },
949 | "execution_count": 20,
950 | "metadata": {},
951 | "output_type": "execute_result"
952 | }
953 | ],
954 | "source": [
955 | "list(map((lambda x: x*2), range(3)))"
956 | ]
957 | },
958 | {
959 | "cell_type": "code",
960 | "execution_count": 21,
961 | "metadata": {
962 | "application/vnd.databricks.v1+cell": {
963 | "inputWidgets": {},
964 | "nuid": "cfa3cc70-0b75-46b9-95c9-9cd7153f8755",
965 | "showTitle": false,
966 | "title": ""
967 | }
968 | },
969 | "outputs": [
970 | {
971 | "data": {
972 | "text/plain": [
973 | "['A', 'B', 'C']"
974 | ]
975 | },
976 | "execution_count": 21,
977 | "metadata": {},
978 | "output_type": "execute_result"
979 | }
980 | ],
981 | "source": [
982 | "list(map((lambda x: x.upper()), 'abc'))"
983 | ]
984 | },
985 | {
986 | "cell_type": "code",
987 | "execution_count": 22,
988 | "metadata": {
989 | "application/vnd.databricks.v1+cell": {
990 | "inputWidgets": {},
991 | "nuid": "eee521b8-5648-489c-91bf-27fdda9b9325",
992 | "showTitle": false,
993 | "title": ""
994 | }
995 | },
996 | "outputs": [
997 | {
998 | "data": {
999 | "text/plain": [
1000 | "['Cat', 'Dog', 'Cow']"
1001 | ]
1002 | },
1003 | "execution_count": 22,
1004 | "metadata": {},
1005 | "output_type": "execute_result"
1006 | }
1007 | ],
1008 | "source": [
1009 | "list(map(lambda x:x.capitalize(), ['cat', 'dog', 'cow']))"
1010 | ]
1011 | },
1012 | {
1013 | "cell_type": "markdown",
1014 | "metadata": {
1015 | "application/vnd.databricks.v1+cell": {
1016 | "inputWidgets": {},
1017 | "nuid": "aaecb617-7cac-4829-85a6-41eb34cedf68",
1018 | "showTitle": false,
1019 | "title": ""
1020 | }
1021 | },
1022 | "source": [
1023 | "`filter()` function is similar to the map(). It takes a function and applies it to each item in the list to create a new list with only those items that cause the function to return True."
1024 | ]
1025 | },
1026 | {
1027 | "cell_type": "code",
1028 | "execution_count": 23,
1029 | "metadata": {
1030 | "application/vnd.databricks.v1+cell": {
1031 | "inputWidgets": {},
1032 | "nuid": "825a75c9-51db-47c0-b8bf-55b166b64a19",
1033 | "showTitle": false,
1034 | "title": ""
1035 | }
1036 | },
1037 | "outputs": [
1038 | {
1039 | "data": {
1040 | "text/plain": [
1041 | "['dog', 'cow']"
1042 | ]
1043 | },
1044 | "execution_count": 23,
1045 | "metadata": {},
1046 | "output_type": "execute_result"
1047 | }
1048 | ],
1049 | "source": [
1050 | "list(filter(lambda x: 'o' in x, ['cat', 'dog', 'cow']))"
1051 | ]
1052 | },
1053 | {
1054 | "cell_type": "markdown",
1055 | "metadata": {
1056 | "application/vnd.databricks.v1+cell": {
1057 | "inputWidgets": {},
1058 | "nuid": "293147a2-9bbd-4878-ae20-bab9591420cb",
1059 | "showTitle": false,
1060 | "title": ""
1061 | }
1062 | },
1063 | "source": [
1064 | "`reduce()` applies a rolling calculation to all items in a list."
1065 | ]
1066 | },
1067 | {
1068 | "cell_type": "code",
1069 | "execution_count": 24,
1070 | "metadata": {
1071 | "application/vnd.databricks.v1+cell": {
1072 | "inputWidgets": {},
1073 | "nuid": "1481643a-fcee-4abd-9596-d73a34b2b5ca",
1074 | "showTitle": false,
1075 | "title": ""
1076 | }
1077 | },
1078 | "outputs": [
1079 | {
1080 | "data": {
1081 | "text/plain": [
1082 | "'cat | dog | cow'"
1083 | ]
1084 | },
1085 | "execution_count": 24,
1086 | "metadata": {},
1087 | "output_type": "execute_result"
1088 | }
1089 | ],
1090 | "source": [
1091 | "from functools import reduce\n",
1092 | "reduce(lambda acc, x: f'{acc} | {x}', ['cat', 'dog', 'cow'])"
1093 | ]
1094 | },
1095 | {
1096 | "cell_type": "markdown",
1097 | "metadata": {
1098 | "application/vnd.databricks.v1+cell": {
1099 | "inputWidgets": {},
1100 | "nuid": "6cbdc0fd-ed98-4143-b110-f9b6dccae802",
1101 | "showTitle": false,
1102 | "title": ""
1103 | }
1104 | },
1105 | "source": [
1106 | "**if else in a lambda**"
1107 | ]
1108 | },
1109 | {
1110 | "cell_type": "code",
1111 | "execution_count": 25,
1112 | "metadata": {
1113 | "application/vnd.databricks.v1+cell": {
1114 | "inputWidgets": {},
1115 | "nuid": "7e09eac6-14c7-4f3f-8cc8-131c13b87e8d",
1116 | "showTitle": false,
1117 | "title": ""
1118 | }
1119 | },
1120 | "outputs": [
1121 | {
1122 | "name": "stdout",
1123 | "output_type": "stream",
1124 | "text": [
1125 | "2\n"
1126 | ]
1127 | }
1128 | ],
1129 | "source": [
1130 | "exp = lambda x, y: x if x < y else y\n",
1131 | "\n",
1132 | "print(exp(2, 4))"
1133 | ]
1134 | },
1135 | {
1136 | "cell_type": "markdown",
1137 | "metadata": {
1138 | "application/vnd.databricks.v1+cell": {
1139 | "inputWidgets": {},
1140 | "nuid": "7fe858a3-e5dc-48ff-a4b6-123c8249ec35",
1141 | "showTitle": false,
1142 | "title": ""
1143 | }
1144 | },
1145 | "source": [
1146 | "**List comprehension in a lambda**"
1147 | ]
1148 | },
1149 | {
1150 | "cell_type": "code",
1151 | "execution_count": 26,
1152 | "metadata": {
1153 | "application/vnd.databricks.v1+cell": {
1154 | "inputWidgets": {},
1155 | "nuid": "06c9cfbb-dd5b-458c-81da-2e380ba7e4c8",
1156 | "showTitle": false,
1157 | "title": ""
1158 | }
1159 | },
1160 | "outputs": [
1161 | {
1162 | "name": "stdout",
1163 | "output_type": "stream",
1164 | "text": [
1165 | "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
1166 | ]
1167 | }
1168 | ],
1169 | "source": [
1170 | "flatten = lambda l: [item for sublist in l for item in sublist]\n",
1171 | "L = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]\n",
1172 | "print(flatten(L))"
1173 | ]
1174 | }
1175 | ],
1176 | "metadata": {
1177 | "anaconda-cloud": {},
1178 | "application/vnd.databricks.v1+notebook": {
1179 | "dashboards": [],
1180 | "language": "python",
1181 | "notebookMetadata": {
1182 | "pythonIndentUnit": 2
1183 | },
1184 | "notebookName": "Python_Functions",
1185 | "notebookOrigID": 3368454474745191,
1186 | "widgets": {}
1187 | },
1188 | "kernelspec": {
1189 | "display_name": "Python 3",
1190 | "language": "python",
1191 | "name": "python3"
1192 | },
1193 | "language_info": {
1194 | "codemirror_mode": {
1195 | "name": "ipython",
1196 | "version": 3
1197 | },
1198 | "file_extension": ".py",
1199 | "mimetype": "text/x-python",
1200 | "name": "python",
1201 | "nbconvert_exporter": "python",
1202 | "pygments_lexer": "ipython3",
1203 | "version": "3.7.3"
1204 | }
1205 | },
1206 | "nbformat": 4,
1207 | "nbformat_minor": 1
1208 | }
1209 |
--------------------------------------------------------------------------------
/Python/.ipynb_checkpoints/Python_Part6-checkpoint.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "application/vnd.databricks.v1+cell": {
7 | "inputWidgets": {},
8 | "nuid": "be705f27-76b4-4600-a38c-17eb65028c91",
9 | "showTitle": false,
10 | "title": ""
11 | }
12 | },
13 | "source": [
14 | "# Decorators\n\nA decorator is a design pattern in Python that allows user to add new functionality to an existing object. Decorators are usually called before the definition of a function you want to decorate. \n\nBefore we try to understand decorators by creating one, let's try to go over a fundamental concept that functions in python are first-class objects. This means that they can be passed as an argument, returend from function, modified and assigned to a variable, just like any other object(string, float, int, etc.)."
15 | ]
16 | },
17 | {
18 | "cell_type": "markdown",
19 | "metadata": {
20 | "application/vnd.databricks.v1+cell": {
21 | "inputWidgets": {},
22 | "nuid": "cbbad752-beb0-4ee0-b282-e1ea8ce1cd4e",
23 | "showTitle": false,
24 | "title": ""
25 | }
26 | },
27 | "source": [
28 | "## Assigning functions to variables\n\nHere, we create a function that will add one to a number whenever it is called. We'll then assign the function to a variable and use this variable to call the function."
29 | ]
30 | },
31 | {
32 | "cell_type": "code",
33 | "execution_count": 0,
34 | "metadata": {
35 | "application/vnd.databricks.v1+cell": {
36 | "inputWidgets": {},
37 | "nuid": "e3bed68f-f56a-4a4b-8ae8-d36074daf439",
38 | "showTitle": false,
39 | "title": ""
40 | }
41 | },
42 | "outputs": [
43 | {
44 | "data": {
45 | "text/plain": [
46 | "Out[1]: 6"
47 | ]
48 | },
49 | "metadata": {
50 | "application/vnd.databricks.v1+output": {
51 | "addedWidgets": {},
52 | "arguments": {},
53 | "data": "Out[1]: 6",
54 | "datasetInfos": [],
55 | "metadata": {},
56 | "removedWidgets": [],
57 | "type": "ansi"
58 | }
59 | },
60 | "output_type": "display_data",
61 | "transient": null
62 | }
63 | ],
64 | "source": [
65 | "def plus_one(number):\n return number + 1\n\nadd_one = plus_one\nadd_one(5)"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "metadata": {
71 | "application/vnd.databricks.v1+cell": {
72 | "inputWidgets": {},
73 | "nuid": "d213ab21-d72e-4bae-8baf-41aa567a8e0c",
74 | "showTitle": false,
75 | "title": ""
76 | }
77 | },
78 | "source": [
79 | "## Defining functions inside other functions\n\nHere, we illustrate how to define a function inside another function."
80 | ]
81 | },
82 | {
83 | "cell_type": "code",
84 | "execution_count": 0,
85 | "metadata": {
86 | "application/vnd.databricks.v1+cell": {
87 | "inputWidgets": {},
88 | "nuid": "613abd42-3bd6-489b-90ad-b7c96cbf167d",
89 | "showTitle": false,
90 | "title": ""
91 | }
92 | },
93 | "outputs": [
94 | {
95 | "data": {
96 | "text/plain": [
97 | "Out[2]: 5"
98 | ]
99 | },
100 | "metadata": {
101 | "application/vnd.databricks.v1+output": {
102 | "addedWidgets": {},
103 | "arguments": {},
104 | "data": "Out[2]: 5",
105 | "datasetInfos": [],
106 | "metadata": {},
107 | "removedWidgets": [],
108 | "type": "ansi"
109 | }
110 | },
111 | "output_type": "display_data",
112 | "transient": null
113 | }
114 | ],
115 | "source": [
116 | "def plus_one(number):\n def add_one(number):\n return number+1\n # assign function to a variable\n result = add_one(number)\n return result\n\nplus_one(4)"
117 | ]
118 | },
119 | {
120 | "cell_type": "markdown",
121 | "metadata": {
122 | "application/vnd.databricks.v1+cell": {
123 | "inputWidgets": {},
124 | "nuid": "cb65da7c-7e0c-4e9b-87ba-10fefe928ad0",
125 | "showTitle": false,
126 | "title": ""
127 | }
128 | },
129 | "source": [
130 | "## Passing functions as arguments to other functions\n\nFunctions can be passed as parameters to other functions."
131 | ]
132 | },
133 | {
134 | "cell_type": "code",
135 | "execution_count": 0,
136 | "metadata": {
137 | "application/vnd.databricks.v1+cell": {
138 | "inputWidgets": {},
139 | "nuid": "5b204555-c3b8-4132-a73d-fc7fc0623e89",
140 | "showTitle": false,
141 | "title": ""
142 | }
143 | },
144 | "outputs": [
145 | {
146 | "data": {
147 | "text/plain": [
148 | "Out[4]: 6"
149 | ]
150 | },
151 | "metadata": {
152 | "application/vnd.databricks.v1+output": {
153 | "addedWidgets": {},
154 | "arguments": {},
155 | "data": "Out[4]: 6",
156 | "datasetInfos": [],
157 | "metadata": {},
158 | "removedWidgets": [],
159 | "type": "ansi"
160 | }
161 | },
162 | "output_type": "display_data",
163 | "transient": null
164 | }
165 | ],
166 | "source": [
167 | "def plus_one(number):\n return number+1\n\ndef function_call(function):\n number_to_add = 5\n return function(number_to_add)\n\nfunction_call(plus_one)"
168 | ]
169 | },
170 | {
171 | "cell_type": "markdown",
172 | "metadata": {
173 | "application/vnd.databricks.v1+cell": {
174 | "inputWidgets": {},
175 | "nuid": "9ea26daf-ed8b-4ec4-a7aa-a0c32ae22b53",
176 | "showTitle": false,
177 | "title": ""
178 | }
179 | },
180 | "source": [
181 | "## Functions returning other functions"
182 | ]
183 | },
184 | {
185 | "cell_type": "code",
186 | "execution_count": 0,
187 | "metadata": {
188 | "application/vnd.databricks.v1+cell": {
189 | "inputWidgets": {},
190 | "nuid": "85e7b62e-fcdb-4dcf-9664-13d2686cc7ee",
191 | "showTitle": false,
192 | "title": ""
193 | }
194 | },
195 | "outputs": [
196 | {
197 | "data": {
198 | "text/plain": [
199 | "Out[6]: 'Hi'"
200 | ]
201 | },
202 | "metadata": {
203 | "application/vnd.databricks.v1+output": {
204 | "addedWidgets": {},
205 | "arguments": {},
206 | "data": "Out[6]: 'Hi'",
207 | "datasetInfos": [],
208 | "metadata": {},
209 | "removedWidgets": [],
210 | "type": "ansi"
211 | }
212 | },
213 | "output_type": "display_data",
214 | "transient": null
215 | }
216 | ],
217 | "source": [
218 | "def hello_function():\n def say_hi():\n return \"Hi\"\n return say_hi\n\nhello = hello_function()\nhello()"
219 | ]
220 | },
221 | {
222 | "cell_type": "code",
223 | "execution_count": 0,
224 | "metadata": {
225 | "application/vnd.databricks.v1+cell": {
226 | "inputWidgets": {},
227 | "nuid": "58e76d22-6cc1-4896-bd6b-a624c3b80ae4",
228 | "showTitle": false,
229 | "title": ""
230 | }
231 | },
232 | "outputs": [
233 | {
234 | "data": {
235 | "text/plain": [
236 | "Running inner\n"
237 | ]
238 | },
239 | "metadata": {
240 | "application/vnd.databricks.v1+output": {
241 | "addedWidgets": {},
242 | "arguments": {},
243 | "data": "Running inner\n",
244 | "datasetInfos": [],
245 | "metadata": {},
246 | "removedWidgets": [],
247 | "type": "ansi"
248 | }
249 | },
250 | "output_type": "display_data",
251 | "transient": null
252 | }
253 | ],
254 | "source": [
255 | "def outer_func():\n def inner_func():\n print ('Running inner')\n inner_func()\n\nouter_func()"
256 | ]
257 | },
258 | {
259 | "cell_type": "code",
260 | "execution_count": 0,
261 | "metadata": {
262 | "application/vnd.databricks.v1+cell": {
263 | "inputWidgets": {},
264 | "nuid": "fcb86ee8-47e4-44e8-8ace-c81bd554e574",
265 | "showTitle": false,
266 | "title": ""
267 | }
268 | },
269 | "outputs": [
270 | {
271 | "data": {
272 | "text/plain": [
273 | "hello\n"
274 | ]
275 | },
276 | "metadata": {
277 | "application/vnd.databricks.v1+output": {
278 | "addedWidgets": {},
279 | "arguments": {},
280 | "data": "hello\n",
281 | "datasetInfos": [],
282 | "metadata": {},
283 | "removedWidgets": [],
284 | "type": "ansi"
285 | }
286 | },
287 | "output_type": "display_data",
288 | "transient": null
289 | }
290 | ],
291 | "source": [
292 | "def to_lower(message):\n def message_sender():\n print(message.lower())\n message_sender()\n\nto_lower(\"HELLO\")"
293 | ]
294 | },
295 | {
296 | "cell_type": "markdown",
297 | "metadata": {
298 | "application/vnd.databricks.v1+cell": {
299 | "inputWidgets": {},
300 | "nuid": "e35f575c-1351-4573-8522-b3a57bc02774",
301 | "showTitle": false,
302 | "title": ""
303 | }
304 | },
305 | "source": [
306 | "## Creating decorators\n\nHere, we create a simple decorator that will convert a sentence to uppercase. First, we define a wrapper function inside an enclosed function. This step is similar to the concept of defining a function inside another function that was showcased earlier."
307 | ]
308 | },
309 | {
310 | "cell_type": "code",
311 | "execution_count": 0,
312 | "metadata": {
313 | "application/vnd.databricks.v1+cell": {
314 | "inputWidgets": {},
315 | "nuid": "c7106b69-e1c2-440f-8d64-615cb2272098",
316 | "showTitle": false,
317 | "title": ""
318 | }
319 | },
320 | "outputs": [],
321 | "source": [
322 | "def uppercase_decorator(function):\n def wrapper():\n func = function()\n make_uppercase = func.upper()\n return make_uppercase\n return wrapper"
323 | ]
324 | },
325 | {
326 | "cell_type": "markdown",
327 | "metadata": {
328 | "application/vnd.databricks.v1+cell": {
329 | "inputWidgets": {},
330 | "nuid": "2e77f06e-4cb3-4223-b04a-56d318dbda78",
331 | "showTitle": false,
332 | "title": ""
333 | }
334 | },
335 | "source": [
336 | "The decorator function takes a function as an argument. So next, we define a function and pass it to our decorator. We learned earlier that we could assign a function to a variable. We'll use that trick to call our decorator function."
337 | ]
338 | },
339 | {
340 | "cell_type": "code",
341 | "execution_count": 0,
342 | "metadata": {
343 | "application/vnd.databricks.v1+cell": {
344 | "inputWidgets": {},
345 | "nuid": "647e9426-c1ff-4994-b0e1-63751effb034",
346 | "showTitle": false,
347 | "title": ""
348 | },
349 | "scrolled": true
350 | },
351 | "outputs": [
352 | {
353 | "data": {
354 | "text/plain": [
355 | "Out[4]: 'HELLO THERE'"
356 | ]
357 | },
358 | "metadata": {
359 | "application/vnd.databricks.v1+output": {
360 | "addedWidgets": {},
361 | "arguments": {},
362 | "data": "Out[4]: 'HELLO THERE'",
363 | "datasetInfos": [],
364 | "metadata": {},
365 | "removedWidgets": [],
366 | "type": "ansi"
367 | }
368 | },
369 | "output_type": "display_data",
370 | "transient": null
371 | }
372 | ],
373 | "source": [
374 | "def say_hi():\n return 'hello there'\ndecorate = uppercase_decorator(say_hi)\ndecorate()"
375 | ]
376 | },
377 | {
378 | "cell_type": "markdown",
379 | "metadata": {
380 | "application/vnd.databricks.v1+cell": {
381 | "inputWidgets": {},
382 | "nuid": "d97df887-d362-4627-9275-3dd80f263889",
383 | "showTitle": false,
384 | "title": ""
385 | }
386 | },
387 | "source": [
388 | "However, Python provides a much easier way for us to apply decorators. We simply use the @ symbol before the function we'd like to decorate. Let's show that in practice below."
389 | ]
390 | },
391 | {
392 | "cell_type": "code",
393 | "execution_count": 0,
394 | "metadata": {
395 | "application/vnd.databricks.v1+cell": {
396 | "inputWidgets": {},
397 | "nuid": "b75a0cc0-896f-4f32-a3ec-b750b0fa57af",
398 | "showTitle": false,
399 | "title": ""
400 | }
401 | },
402 | "outputs": [
403 | {
404 | "data": {
405 | "text/plain": [
406 | "Out[9]: 'HELLO THERE'"
407 | ]
408 | },
409 | "metadata": {
410 | "application/vnd.databricks.v1+output": {
411 | "addedWidgets": {},
412 | "arguments": {},
413 | "data": "Out[9]: 'HELLO THERE'",
414 | "datasetInfos": [],
415 | "metadata": {},
416 | "removedWidgets": [],
417 | "type": "ansi"
418 | }
419 | },
420 | "output_type": "display_data",
421 | "transient": null
422 | }
423 | ],
424 | "source": [
425 | "@uppercase_decorator\ndef say_hi():\n return 'hello there'\nsay_hi()"
426 | ]
427 | },
428 | {
429 | "cell_type": "markdown",
430 | "metadata": {
431 | "application/vnd.databricks.v1+cell": {
432 | "inputWidgets": {},
433 | "nuid": "ca82b011-fb60-4a6d-a2b4-1d179f98aff3",
434 | "showTitle": false,
435 | "title": ""
436 | }
437 | },
438 | "source": [
439 | "**Execution explained**"
440 | ]
441 | },
442 | {
443 | "cell_type": "code",
444 | "execution_count": 0,
445 | "metadata": {
446 | "application/vnd.databricks.v1+cell": {
447 | "inputWidgets": {},
448 | "nuid": "456b204e-cd0c-4b60-97ed-d132e37c8371",
449 | "showTitle": false,
450 | "title": ""
451 | }
452 | },
453 | "outputs": [
454 | {
455 | "data": {
456 | "text/plain": [
457 | "Inside wrapper\nHello world\n"
458 | ]
459 | },
460 | "metadata": {
461 | "application/vnd.databricks.v1+output": {
462 | "addedWidgets": {},
463 | "arguments": {},
464 | "data": "Inside wrapper\nHello world\n",
465 | "datasetInfos": [],
466 | "metadata": {},
467 | "removedWidgets": [],
468 | "type": "ansi"
469 | }
470 | },
471 | "output_type": "display_data",
472 | "transient": null
473 | }
474 | ],
475 | "source": [
476 | "def myWrapper(func):\n def myInnerfunc():\n print(\"Inside wrapper\")\n func()\n return myInnerfunc\n# decorate = myWrapper(myFunc)\n# decorate()\n@myWrapper\ndef myFunc():\n print (\"Hello world\")\nmyFunc()"
477 | ]
478 | },
479 | {
480 | "cell_type": "markdown",
481 | "metadata": {
482 | "application/vnd.databricks.v1+cell": {
483 | "inputWidgets": {},
484 | "nuid": "c833aa3c-bd9f-4436-9a21-f5c4572f37b2",
485 | "showTitle": false,
486 | "title": ""
487 | }
488 | },
489 | "source": [
490 | "
"
491 | ]
492 | },
493 | {
494 | "cell_type": "markdown",
495 | "metadata": {
496 | "application/vnd.databricks.v1+cell": {
497 | "inputWidgets": {},
498 | "nuid": "0c6eae4e-53ed-4574-9ffc-c49687f9fa23",
499 | "showTitle": false,
500 | "title": ""
501 | }
502 | },
503 | "source": [
504 | "Here, we are trying to decorate the `myFunc` function. using the decorator function `myWrapper`. Below are the steps of execution in the above code:\n\n**1. The original function `myFunc` is called.**\n
\n**2. There is a function wrapper name `@myWrapper` specified above the `myFunc` function definition. This indicates, there is a function decorator assigned to the function.**\n
\n**3. The decorator function `myWrapper` gets called. The program controller passes the function object as a parameter to the decorator function.**\n
\n**4. The function `myInnerFunc` inside the decorator function gets executed.**\n
\n**5. The inner function `myInnerFunc` calls the actual function `myFunc`.**\n
\n**6. The original function `myFunc` starts execution.**"
505 | ]
506 | },
507 | {
508 | "cell_type": "markdown",
509 | "metadata": {
510 | "application/vnd.databricks.v1+cell": {
511 | "inputWidgets": {},
512 | "nuid": "8fd21c68-cdaa-4652-a1a4-a89922c99a84",
513 | "showTitle": false,
514 | "title": ""
515 | }
516 | },
517 | "source": [
518 | "## Accepting arguments with decorator functions"
519 | ]
520 | },
521 | {
522 | "cell_type": "code",
523 | "execution_count": 0,
524 | "metadata": {
525 | "application/vnd.databricks.v1+cell": {
526 | "inputWidgets": {},
527 | "nuid": "310cabd3-1637-4d93-b127-beb5abb3925f",
528 | "showTitle": false,
529 | "title": ""
530 | }
531 | },
532 | "outputs": [
533 | {
534 | "data": {
535 | "text/plain": [
536 | "My arguments are: Barcelona, Milan\nCities I love are Barcelona and Milan\n"
537 | ]
538 | },
539 | "metadata": {
540 | "application/vnd.databricks.v1+output": {
541 | "addedWidgets": {},
542 | "arguments": {},
543 | "data": "My arguments are: Barcelona, Milan\nCities I love are Barcelona and Milan\n",
544 | "datasetInfos": [],
545 | "metadata": {},
546 | "removedWidgets": [],
547 | "type": "ansi"
548 | }
549 | },
550 | "output_type": "display_data",
551 | "transient": null
552 | }
553 | ],
554 | "source": [
555 | "def decorator_with_arguments(function):\n def wrapper_accepting_arguments(arg1,arg2):\n print(f\"My arguments are: {arg1}, {arg2}\")\n function(arg1,arg2)\n return wrapper_accepting_arguments\n\n@decorator_with_arguments\ndef cities(city_one,city_two):\n print(f'Cities I love are {city_one} and {city_two}')\n \ncities('Barcelona','Milan')"
556 | ]
557 | },
558 | {
559 | "cell_type": "markdown",
560 | "metadata": {
561 | "application/vnd.databricks.v1+cell": {
562 | "inputWidgets": {},
563 | "nuid": "382e334e-3769-4c74-9ee7-38fed010db5d",
564 | "showTitle": false,
565 | "title": ""
566 | }
567 | },
568 | "source": [
569 | "## Passing arguments to the decorator"
570 | ]
571 | },
572 | {
573 | "cell_type": "code",
574 | "execution_count": 0,
575 | "metadata": {
576 | "application/vnd.databricks.v1+cell": {
577 | "inputWidgets": {},
578 | "nuid": "753ba376-da9d-4531-af18-c871314ea60a",
579 | "showTitle": false,
580 | "title": ""
581 | }
582 | },
583 | "outputs": [
584 | {
585 | "data": {
586 | "text/plain": [
587 | "The wrapper can access all the variables from the decorator maker: \n Pandas Numpy Scikit-learn from the function call: \n Pandas Science Tools \n and pass them to the decorated function\nThis is the decorated function and it only knows about its arguments: \n Pandas Science Tools\n"
588 | ]
589 | },
590 | "metadata": {
591 | "application/vnd.databricks.v1+output": {
592 | "addedWidgets": {},
593 | "arguments": {},
594 | "data": "The wrapper can access all the variables from the decorator maker: \n Pandas Numpy Scikit-learn from the function call: \n Pandas Science Tools \n and pass them to the decorated function\nThis is the decorated function and it only knows about its arguments: \n Pandas Science Tools\n",
595 | "datasetInfos": [],
596 | "metadata": {},
597 | "removedWidgets": [],
598 | "type": "ansi"
599 | }
600 | },
601 | "output_type": "display_data",
602 | "transient": null
603 | }
604 | ],
605 | "source": [
606 | "def decorator_maker_with_arguments(decorator_arg1, decorator_arg2, decorator_arg3):\n def decorator(func):\n def wrapper(function_arg1, function_arg2, function_arg3) :\n \"This is the wrapper function\"\n print(f'The wrapper can access all the variables from the decorator maker: \\n\\\n {decorator_arg1} {decorator_arg2} {decorator_arg3} from the function call: \\n\\\n {function_arg1} {function_arg2} {function_arg3} \\n\\\n and pass them to the decorated function')\n \n return func(function_arg1, function_arg2,function_arg3)\n\n return wrapper\n\n return decorator\n\npandas = \"Pandas\"\n@decorator_maker_with_arguments(pandas, \"Numpy\",\"Scikit-learn\")\ndef decorated_function_with_arguments(function_arg1, function_arg2,function_arg3):\n print(f\"This is the decorated function and it only knows about its arguments: \\n\\\n {function_arg1} {function_arg2} {function_arg3}\")\n\ndecorated_function_with_arguments(pandas, \"Science\", \"Tools\")"
607 | ]
608 | },
609 | {
610 | "cell_type": "markdown",
611 | "metadata": {
612 | "application/vnd.databricks.v1+cell": {
613 | "inputWidgets": {},
614 | "nuid": "be36c628-d969-4915-bd1e-323b00d73993",
615 | "showTitle": false,
616 | "title": ""
617 | }
618 | },
619 | "source": [
620 | "## Classes as decorators\n\nThere are two ways of using decorators with classes; one can either decorate the individual methods inside the class or decorate the whole class. The below example refers to the latter.\n\nAs mentioned earlier, the decorator syntax `@uppercase_decorator` is just an easier way of saying `func = uppercase_decorator(func)`. Therefore, if `uppercase_decorator` is a class, it needs to take func as an argument in its `.__init__()` method. Furthermore, the class instance needs to be callable so that it can stand in for the decorated function.\n\nFor a class instance to be callable, you implement the special `.__call__()` method:\n\nThe `.__init__()` method must store a reference to the function and can do any other necessary initialization. The `.__call__()` method will be called instead of the decorated function. It does essentially the same thing as the wrapper() function in our earlier examples."
621 | ]
622 | },
623 | {
624 | "cell_type": "code",
625 | "execution_count": 0,
626 | "metadata": {
627 | "application/vnd.databricks.v1+cell": {
628 | "inputWidgets": {},
629 | "nuid": "9e6fab53-3818-4eec-ac9e-ddc4beec1b75",
630 | "showTitle": false,
631 | "title": ""
632 | }
633 | },
634 | "outputs": [
635 | {
636 | "data": {
637 | "text/plain": [
638 | "Hello there!\n"
639 | ]
640 | },
641 | "metadata": {
642 | "application/vnd.databricks.v1+output": {
643 | "addedWidgets": {},
644 | "arguments": {},
645 | "data": "Hello there!\n",
646 | "datasetInfos": [],
647 | "metadata": {},
648 | "removedWidgets": [],
649 | "type": "ansi"
650 | }
651 | },
652 | "output_type": "display_data",
653 | "transient": null
654 | }
655 | ],
656 | "source": [
657 | "class mydecorator:\n def __init__(self, function):\n self.function = function\n \n def __call__(self):\n \n # We can add some code\n # before function call\n \n func = self.function()\n \n # We can also add some code\n # after function call.\n return \n \n \n# adding class decorator to the function\n@mydecorator\ndef function():\n print(\"Hello there!\")\n\nfunction()"
658 | ]
659 | },
660 | {
661 | "cell_type": "markdown",
662 | "metadata": {
663 | "application/vnd.databricks.v1+cell": {
664 | "inputWidgets": {},
665 | "nuid": "9686aef0-98dd-460e-b740-faa95ed11f45",
666 | "showTitle": false,
667 | "title": ""
668 | }
669 | },
670 | "source": [
671 | "Implementing the earlier example by using classes as decorators"
672 | ]
673 | },
674 | {
675 | "cell_type": "code",
676 | "execution_count": 0,
677 | "metadata": {
678 | "application/vnd.databricks.v1+cell": {
679 | "inputWidgets": {},
680 | "nuid": "58a37d0a-fbbc-4c0f-a03c-534104304258",
681 | "showTitle": false,
682 | "title": ""
683 | }
684 | },
685 | "outputs": [
686 | {
687 | "data": {
688 | "text/plain": [
689 | "Out[17]: 'HELLO THERE!'"
690 | ]
691 | },
692 | "metadata": {
693 | "application/vnd.databricks.v1+output": {
694 | "addedWidgets": {},
695 | "arguments": {},
696 | "data": "Out[17]: 'HELLO THERE!'",
697 | "datasetInfos": [],
698 | "metadata": {},
699 | "removedWidgets": [],
700 | "type": "ansi"
701 | }
702 | },
703 | "output_type": "display_data",
704 | "transient": null
705 | }
706 | ],
707 | "source": [
708 | "class uppercase_decorator:\n def __init__(self, function):\n self.function = function\n \n def __call__(self):\n func = self.function()\n make_uppercase = func.upper()\n return make_uppercase\n \n \n# adding class decorator to the function\n@uppercase_decorator\ndef function():\n return \"Hello there!\"\n\nfunction()"
709 | ]
710 | },
711 | {
712 | "cell_type": "code",
713 | "execution_count": 0,
714 | "metadata": {
715 | "application/vnd.databricks.v1+cell": {
716 | "inputWidgets": {},
717 | "nuid": "0f379f89-7601-4d5c-9252-808cf009b458",
718 | "showTitle": false,
719 | "title": ""
720 | }
721 | },
722 | "outputs": [],
723 | "source": [
724 | "class mydecorator:\n def __init__(self,func):\n self.func = func\n \n def __call__(self,*args,**kwargs):\n self.func(*args,**kwargs)\n\n\n@mydecorator\ndef function(name, message ='Hello'):\n return(f\"{message}, {name}\")\n\nfunction(\"geeks_for_geeks\", \"hello\")"
725 | ]
726 | },
727 | {
728 | "cell_type": "markdown",
729 | "metadata": {
730 | "application/vnd.databricks.v1+cell": {
731 | "inputWidgets": {},
732 | "nuid": "44d5f087-9271-4843-a907-d43cc483a378",
733 | "showTitle": false,
734 | "title": ""
735 | }
736 | },
737 | "source": [
738 | "## Decorating classes\n\nThree of the most common Python decorators are used for decorating class methods:\n- `@property` is used to create property attributes that can only be accessed through its getter, setter, and deleter methods.\n\n- `@staticmethod` and `@classmethod` are used to define class methods that are not connected to particular instances of the class. Static methods don’t require an argument, while class methods take the class as an argument."
739 | ]
740 | },
741 | {
742 | "cell_type": "code",
743 | "execution_count": 0,
744 | "metadata": {
745 | "application/vnd.databricks.v1+cell": {
746 | "inputWidgets": {},
747 | "nuid": "3deb212b-4785-4885-9d7d-3ac9104bd51e",
748 | "showTitle": false,
749 | "title": ""
750 | }
751 | },
752 | "outputs": [
753 | {
754 | "data": {
755 | "text/plain": [
756 | "39825.75\n98621.75\n"
757 | ]
758 | },
759 | "metadata": {
760 | "application/vnd.databricks.v1+output": {
761 | "addedWidgets": {},
762 | "arguments": {},
763 | "data": "39825.75\n98621.75\n",
764 | "datasetInfos": [],
765 | "metadata": {},
766 | "removedWidgets": [],
767 | "type": "ansi"
768 | }
769 | },
770 | "output_type": "display_data",
771 | "transient": null
772 | }
773 | ],
774 | "source": [
775 | "class Account:\n def __init__(self, balance):\n self._balance = balance\n @property\n def balance(self):\n \"\"\"Gets balance\"\"\"\n return self._balance\n \n @balance.setter\n def balance(self, value):\n \"\"\"Set balance, raise error if negative\"\"\"\n if value >= 0:\n self._balance = value\n else:\n raise ValueError(\"balance must be positive\")\n \n @classmethod\n def new_account(cls):\n \"\"\"Returns a new account with 100.00 balance\"\"\"\n return cls(100.00)\n \n @staticmethod\n def interest():\n \"\"\"The interest rate\"\"\"\n return 5.25\n\n\nacc = Account(39825.75)\nprint(acc.balance)\nacc.balance = 98621.75\nprint(acc.balance)"
776 | ]
777 | }
778 | ],
779 | "metadata": {
780 | "anaconda-cloud": {},
781 | "application/vnd.databricks.v1+notebook": {
782 | "dashboards": [],
783 | "language": "python",
784 | "notebookMetadata": {
785 | "pythonIndentUnit": 2
786 | },
787 | "notebookName": "Python_Part5",
788 | "notebookOrigID": 3085993468102599,
789 | "widgets": {}
790 | },
791 | "kernelspec": {
792 | "display_name": "Python [conda env:Covid_Lookback-Py3]",
793 | "language": "python",
794 | "name": "conda-env-Covid_Lookback-Py3-py"
795 | },
796 | "language_info": {
797 | "codemirror_mode": {
798 | "name": "ipython",
799 | "version": 3
800 | },
801 | "file_extension": ".py",
802 | "mimetype": "text/x-python",
803 | "name": "python",
804 | "nbconvert_exporter": "python",
805 | "pygments_lexer": "ipython3",
806 | "version": "3.7.9"
807 | }
808 | },
809 | "nbformat": 4,
810 | "nbformat_minor": 0
811 | }
812 |
--------------------------------------------------------------------------------
/Python/Python_Part2.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "application/vnd.databricks.v1+cell": {
7 | "inputWidgets": {},
8 | "nuid": "85b36ae8-5cea-48da-84f7-4bbd359b6fe9",
9 | "showTitle": false,
10 | "title": ""
11 | }
12 | },
13 | "source": [
14 | "# Python for Data Science and Machine Learning - Part 2\n",
15 | "\n",
16 | "----\n",
17 | "\n",
18 | "\n",
19 | "**Dictionary continued...**\n",
20 | "\n",
21 | "Other ways to create dictionaries"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": 1,
27 | "metadata": {
28 | "application/vnd.databricks.v1+cell": {
29 | "inputWidgets": {},
30 | "nuid": "2493a889-ea91-43df-b65e-9e859cea4e03",
31 | "showTitle": false,
32 | "title": ""
33 | }
34 | },
35 | "outputs": [
36 | {
37 | "data": {
38 | "text/plain": [
39 | "{'model': 'Beetle', 'year': 2021, 'maker': 'Volkswagon'}"
40 | ]
41 | },
42 | "execution_count": 1,
43 | "metadata": {},
44 | "output_type": "execute_result"
45 | }
46 | ],
47 | "source": [
48 | "# Create a dictionary with list of zipped keys/values\n",
49 | "keys = ['model', 'year', 'maker']\n",
50 | "values = ['Beetle', 2021, 'Volkswagon']\n",
51 | "\n",
52 | "D = dict(zip(keys,values))\n",
53 | "D"
54 | ]
55 | },
56 | {
57 | "cell_type": "markdown",
58 | "metadata": {
59 | "application/vnd.databricks.v1+cell": {
60 | "inputWidgets": {},
61 | "nuid": "3a29eb64-b946-4746-8939-b5c803737ac8",
62 | "showTitle": false,
63 | "title": ""
64 | }
65 | },
66 | "source": [
67 | "Note: Keys must be unique. If a key is specified more than once while the creation of a dictionary, the last value for that key becomes the associated value."
68 | ]
69 | },
70 | {
71 | "cell_type": "code",
72 | "execution_count": 2,
73 | "metadata": {
74 | "application/vnd.databricks.v1+cell": {
75 | "inputWidgets": {},
76 | "nuid": "326a15da-694d-4c5e-8b09-7389cecd47fd",
77 | "showTitle": false,
78 | "title": ""
79 | }
80 | },
81 | "outputs": [
82 | {
83 | "name": "stdout",
84 | "output_type": "stream",
85 | "text": [
86 | "{'model': 'Jetta', 'year': 2021}\n"
87 | ]
88 | }
89 | ],
90 | "source": [
91 | "D = {'model': 'Beetle',\n",
92 | " 'year': 2021,\n",
93 | " 'model': 'Jetta'}\n",
94 | "print(D)"
95 | ]
96 | },
97 | {
98 | "cell_type": "markdown",
99 | "metadata": {
100 | "application/vnd.databricks.v1+cell": {
101 | "inputWidgets": {},
102 | "nuid": "41994238-4e17-42d0-8c0c-d639228fa3de",
103 | "showTitle": false,
104 | "title": ""
105 | }
106 | },
107 | "source": [
108 | "Create a dictionary with default values for each key. The `fromkeys()` method offers a way to do this."
109 | ]
110 | },
111 | {
112 | "cell_type": "code",
113 | "execution_count": 3,
114 | "metadata": {
115 | "application/vnd.databricks.v1+cell": {
116 | "inputWidgets": {},
117 | "nuid": "97531796-c422-4385-b23d-6907df464505",
118 | "showTitle": false,
119 | "title": ""
120 | }
121 | },
122 | "outputs": [
123 | {
124 | "data": {
125 | "text/plain": [
126 | "{'x': 0, 'y': 0, 'z': 0}"
127 | ]
128 | },
129 | "execution_count": 3,
130 | "metadata": {},
131 | "output_type": "execute_result"
132 | }
133 | ],
134 | "source": [
135 | "# Initialize a dictionary with default value '0' for each key\n",
136 | "keys = ['x', 'y', 'z']\n",
137 | "defaultValue = 0\n",
138 | "\n",
139 | "D = dict.fromkeys(keys,defaultValue)\n",
140 | "D"
141 | ]
142 | },
143 | {
144 | "cell_type": "code",
145 | "execution_count": 4,
146 | "metadata": {
147 | "application/vnd.databricks.v1+cell": {
148 | "inputWidgets": {},
149 | "nuid": "17910056-6bc5-4f05-9160-fff5d50bd936",
150 | "showTitle": false,
151 | "title": ""
152 | }
153 | },
154 | "outputs": [
155 | {
156 | "name": "stdout",
157 | "output_type": "stream",
158 | "text": [
159 | "{'a': [1, 2, 3], 'b': {1, 2, 3}}\n",
160 | "{'a': [1, 2], 'b': [1, 2], 'c': [1, 2]}\n"
161 | ]
162 | }
163 | ],
164 | "source": [
165 | "D = {'a':[1,2,3],\n",
166 | " 'b':{1,2,3}}\n",
167 | "print (D)\n",
168 | "\n",
169 | "# duplicate values\n",
170 | "D = {'a':[1,2],\n",
171 | " 'b':[1,2],\n",
172 | " 'c':[1,2]}\n",
173 | "print (D)"
174 | ]
175 | },
176 | {
177 | "cell_type": "markdown",
178 | "metadata": {
179 | "application/vnd.databricks.v1+cell": {
180 | "inputWidgets": {},
181 | "nuid": "1d1251bd-819c-45a7-8a00-acc09d700967",
182 | "showTitle": false,
183 | "title": ""
184 | }
185 | },
186 | "source": [
187 | "**Merge two dictionaries**"
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": 5,
193 | "metadata": {
194 | "application/vnd.databricks.v1+cell": {
195 | "inputWidgets": {},
196 | "nuid": "31411200-dc8c-43e3-99c9-10c8d1b1dac3",
197 | "showTitle": false,
198 | "title": ""
199 | }
200 | },
201 | "outputs": [
202 | {
203 | "data": {
204 | "text/plain": [
205 | "{'model': 'Jetta', 'year': 2020, 'fuel': 'Solar', 'capacity': 4}"
206 | ]
207 | },
208 | "execution_count": 5,
209 | "metadata": {},
210 | "output_type": "execute_result"
211 | }
212 | ],
213 | "source": [
214 | "D1 = {'model': 'Beetle',\n",
215 | " 'year': 2021,\n",
216 | " 'model': 'Jetta'}\n",
217 | "\n",
218 | "D2 = {'year': 2020,\n",
219 | " 'fuel': 'Solar',\n",
220 | " 'capacity': 4}\n",
221 | "\n",
222 | "D1.update(D2)\n",
223 | "D1"
224 | ]
225 | },
226 | {
227 | "cell_type": "markdown",
228 | "metadata": {
229 | "application/vnd.databricks.v1+cell": {
230 | "inputWidgets": {},
231 | "nuid": "fb08f113-c8cc-445a-b61b-9a6751be4bbd",
232 | "showTitle": false,
233 | "title": ""
234 | }
235 | },
236 | "source": [
237 | "**Remove an Item by Key**\n",
238 | "\n",
239 | "If you know the key of the item you want, you can use pop() method. It removes the key and returns its value."
240 | ]
241 | },
242 | {
243 | "cell_type": "code",
244 | "execution_count": 6,
245 | "metadata": {
246 | "application/vnd.databricks.v1+cell": {
247 | "inputWidgets": {},
248 | "nuid": "99ca58f4-f3b2-48d9-a0ef-4dcfea1c789e",
249 | "showTitle": false,
250 | "title": ""
251 | }
252 | },
253 | "outputs": [
254 | {
255 | "name": "stdout",
256 | "output_type": "stream",
257 | "text": [
258 | "{'model': 'Beetle', 'maker': 'Volkswagon'}\n",
259 | "2021\n"
260 | ]
261 | }
262 | ],
263 | "source": [
264 | "D = {'model': 'Beetle',\n",
265 | " 'year': 2021,\n",
266 | " 'maker': 'Volkswagon'}\n",
267 | "\n",
268 | "x = D.pop('year')\n",
269 | "print(D)\n",
270 | "\n",
271 | "# get removed value\n",
272 | "print(x)"
273 | ]
274 | },
275 | {
276 | "cell_type": "markdown",
277 | "metadata": {
278 | "application/vnd.databricks.v1+cell": {
279 | "inputWidgets": {},
280 | "nuid": "c34868c8-57b5-4500-9a7c-3d488f5c2284",
281 | "showTitle": false,
282 | "title": ""
283 | }
284 | },
285 | "source": [
286 | "Get All Keys, Values and Key:Value Pairs"
287 | ]
288 | },
289 | {
290 | "cell_type": "code",
291 | "execution_count": 7,
292 | "metadata": {
293 | "application/vnd.databricks.v1+cell": {
294 | "inputWidgets": {},
295 | "nuid": "c22c2958-18ae-4feb-86b6-9854f454152a",
296 | "showTitle": false,
297 | "title": ""
298 | }
299 | },
300 | "outputs": [
301 | {
302 | "name": "stdout",
303 | "output_type": "stream",
304 | "text": [
305 | "['model', 'year', 'maker']\n",
306 | "['Beetle', 2021, 'Volkswagon']\n",
307 | "[('model', 'Beetle'), ('year', 2021), ('maker', 'Volkswagon')]\n"
308 | ]
309 | }
310 | ],
311 | "source": [
312 | "D = {'model': 'Beetle',\n",
313 | " 'year': 2021,\n",
314 | " 'maker': 'Volkswagon'}\n",
315 | "\n",
316 | "# get all keys\n",
317 | "print(list(D.keys()))\n",
318 | "\n",
319 | "\n",
320 | "# get all values\n",
321 | "print(list(D.values()))\n",
322 | "\n",
323 | "# get all pairs\n",
324 | "print(list(D.items()))"
325 | ]
326 | },
327 | {
328 | "cell_type": "markdown",
329 | "metadata": {
330 | "application/vnd.databricks.v1+cell": {
331 | "inputWidgets": {},
332 | "nuid": "f3092742-3264-40b8-9ff1-498a835105f3",
333 | "showTitle": false,
334 | "title": ""
335 | }
336 | },
337 | "source": [
338 | "Iterate through a dictionary. If you use a dictionary in a for loop, it traverses the keys of the dictionary by default."
339 | ]
340 | },
341 | {
342 | "cell_type": "code",
343 | "execution_count": 8,
344 | "metadata": {
345 | "application/vnd.databricks.v1+cell": {
346 | "inputWidgets": {},
347 | "nuid": "0bab42c1-a1e7-4500-b1d5-1e5422f7473a",
348 | "showTitle": false,
349 | "title": ""
350 | },
351 | "scrolled": true
352 | },
353 | "outputs": [
354 | {
355 | "name": "stdout",
356 | "output_type": "stream",
357 | "text": [
358 | "model\n",
359 | "year\n",
360 | "maker\n"
361 | ]
362 | }
363 | ],
364 | "source": [
365 | "D = {'model': 'Beetle',\n",
366 | " 'year': 2021,\n",
367 | " 'maker': 'Volkswagon'}\n",
368 | "\n",
369 | "for x in D:\n",
370 | " print(x)"
371 | ]
372 | },
373 | {
374 | "cell_type": "markdown",
375 | "metadata": {
376 | "application/vnd.databricks.v1+cell": {
377 | "inputWidgets": {},
378 | "nuid": "f35a9dad-36ee-457e-970f-695dae7c8a9b",
379 | "showTitle": false,
380 | "title": ""
381 | }
382 | },
383 | "source": [
384 | "To iterate over the values of a dictionary, index from key to value inside the for loop."
385 | ]
386 | },
387 | {
388 | "cell_type": "code",
389 | "execution_count": 9,
390 | "metadata": {
391 | "application/vnd.databricks.v1+cell": {
392 | "inputWidgets": {},
393 | "nuid": "455d333f-4770-4ccc-af44-ac068c34caed",
394 | "showTitle": false,
395 | "title": ""
396 | },
397 | "scrolled": true
398 | },
399 | "outputs": [
400 | {
401 | "name": "stdout",
402 | "output_type": "stream",
403 | "text": [
404 | "Beetle\n",
405 | "2021\n",
406 | "Volkswagon\n"
407 | ]
408 | }
409 | ],
410 | "source": [
411 | "D = {'model': 'Beetle',\n",
412 | " 'year': 2021,\n",
413 | " 'maker': 'Volkswagon'}\n",
414 | "\n",
415 | "for x in D:\n",
416 | " print(D[x])"
417 | ]
418 | },
419 | {
420 | "cell_type": "markdown",
421 | "metadata": {
422 | "application/vnd.databricks.v1+cell": {
423 | "inputWidgets": {},
424 | "nuid": "bf9c85de-dc42-4ed6-9d4e-cd9175200a9b",
425 | "showTitle": false,
426 | "title": ""
427 | }
428 | },
429 | "source": [
430 | "**Python Dictionary Methods**\n",
431 | "\n",
432 | "| Syntax | Description |\n",
433 | "| :------------ | :----------- |\n",
434 | "| `clear()` | Removes all items from the dictionary |\n",
435 | "| `copy()` | Returns a shallow copy of the dictionary |\n",
436 | "| `fromkeys()` | Creates a new dictionary with the specified keys and values |\n",
437 | "| `get()` | Returns the value of the specified key |\n",
438 | "| `items()` | Returns a list of key:value pair |\n",
439 | "| `keys()` | Returns a list of all keys from dictionary |\n",
440 | "| `pop()` | Removes and returns single dictionary item with specified key. |\n",
441 | "| `popitem()` | Removes and returns last inserted key:value pair from the dictionary. |\n",
442 | "| `setdefault()` | Returns the value of the specified key, if present. Else, inserts the key with a specified value. |\n",
443 | "| `update()` | Updates the dictionary with the specified key:value pairs |\n",
444 | "| `values()` | Returns a list of all values from dictionary |"
445 | ]
446 | },
447 | {
448 | "cell_type": "markdown",
449 | "metadata": {
450 | "application/vnd.databricks.v1+cell": {
451 | "inputWidgets": {},
452 | "nuid": "342b65ca-6734-4e64-bdb9-5f9c8230e73b",
453 | "showTitle": false,
454 | "title": ""
455 | }
456 | },
457 | "source": [
458 | "# Comprehension\n",
459 | "\n",
460 | "A comprehension is a compact way of creating a Python data structure from iterators. With comprehensions, you can combine loops and conditional tests with a less verbose syntax."
461 | ]
462 | },
463 | {
464 | "cell_type": "markdown",
465 | "metadata": {
466 | "application/vnd.databricks.v1+cell": {
467 | "inputWidgets": {},
468 | "nuid": "756114c4-269f-4ca7-9b3a-e30afe9641e4",
469 | "showTitle": false,
470 | "title": ""
471 | }
472 | },
473 | "source": [
474 | "**List Comprehension**\n",
475 | "\n",
476 | "Suppose you want to create a list of all integer square numbers from 0 to 4. You could build that list by appending one item at a time to an empty list:"
477 | ]
478 | },
479 | {
480 | "cell_type": "code",
481 | "execution_count": 10,
482 | "metadata": {
483 | "application/vnd.databricks.v1+cell": {
484 | "inputWidgets": {},
485 | "nuid": "fb772592-e08b-45f2-be76-3072d408366d",
486 | "showTitle": false,
487 | "title": ""
488 | }
489 | },
490 | "outputs": [
491 | {
492 | "name": "stdout",
493 | "output_type": "stream",
494 | "text": [
495 | "[0, 1, 4, 9, 16]\n"
496 | ]
497 | }
498 | ],
499 | "source": [
500 | "L = []\n",
501 | "for x in range(5):\n",
502 | " L.append(x**2)\n",
503 | "print(L)"
504 | ]
505 | },
506 | {
507 | "cell_type": "markdown",
508 | "metadata": {
509 | "application/vnd.databricks.v1+cell": {
510 | "inputWidgets": {},
511 | "nuid": "41063713-56a7-4dea-9b33-f956c6842eb5",
512 | "showTitle": false,
513 | "title": ""
514 | }
515 | },
516 | "source": [
517 | "Here both approaches produce the same result. However, a more Pythonic way to build a list is by using a list comprehension.\n",
518 | "\n",
519 | "The general syntax for a list comprehension is:\n",
520 | "\n",
521 | "
\n",
522 | "\n",
523 | "Here’s how a list comprehension would build the above list:"
524 | ]
525 | },
526 | {
527 | "cell_type": "code",
528 | "execution_count": 11,
529 | "metadata": {
530 | "application/vnd.databricks.v1+cell": {
531 | "inputWidgets": {},
532 | "nuid": "072f31fa-073a-41d1-b56c-109a3ff32d07",
533 | "showTitle": false,
534 | "title": ""
535 | }
536 | },
537 | "outputs": [
538 | {
539 | "name": "stdout",
540 | "output_type": "stream",
541 | "text": [
542 | "[0, 1, 4, 9, 16]\n"
543 | ]
544 | }
545 | ],
546 | "source": [
547 | "L = [x**2 for x in range(5)]\n",
548 | "print(L)"
549 | ]
550 | },
551 | {
552 | "cell_type": "code",
553 | "execution_count": 12,
554 | "metadata": {
555 | "application/vnd.databricks.v1+cell": {
556 | "inputWidgets": {},
557 | "nuid": "76ec0597-d6d3-4f1b-8b94-f844e4eb1705",
558 | "showTitle": false,
559 | "title": ""
560 | }
561 | },
562 | "outputs": [
563 | {
564 | "name": "stdout",
565 | "output_type": "stream",
566 | "text": [
567 | "['RRR', 'EEE', 'DDD']\n"
568 | ]
569 | }
570 | ],
571 | "source": [
572 | "L = [x*3 for x in 'RED']\n",
573 | "print(L)"
574 | ]
575 | },
576 | {
577 | "cell_type": "code",
578 | "execution_count": 13,
579 | "metadata": {
580 | "application/vnd.databricks.v1+cell": {
581 | "inputWidgets": {},
582 | "nuid": "dfe09d7d-4248-4622-8319-541760aeb875",
583 | "showTitle": false,
584 | "title": ""
585 | }
586 | },
587 | "outputs": [
588 | {
589 | "data": {
590 | "text/plain": [
591 | "['red', 'green', 'blue']"
592 | ]
593 | },
594 | "execution_count": 13,
595 | "metadata": {},
596 | "output_type": "execute_result"
597 | }
598 | ],
599 | "source": [
600 | "colors = [' red', ' green ', 'blue ']\n",
601 | "L = [color.strip() for color in colors]\n",
602 | "L"
603 | ]
604 | },
605 | {
606 | "cell_type": "code",
607 | "execution_count": 14,
608 | "metadata": {
609 | "application/vnd.databricks.v1+cell": {
610 | "inputWidgets": {},
611 | "nuid": "76d63715-8d89-4ec7-9421-d229b3b3c546",
612 | "showTitle": false,
613 | "title": ""
614 | },
615 | "scrolled": true
616 | },
617 | "outputs": [
618 | {
619 | "name": "stdout",
620 | "output_type": "stream",
621 | "text": [
622 | "[(0, 0), (1, 1), (2, 4), (3, 9)]\n"
623 | ]
624 | }
625 | ],
626 | "source": [
627 | "L = [(x, x**2) for x in range(4)]\n",
628 | "print(L)"
629 | ]
630 | },
631 | {
632 | "cell_type": "markdown",
633 | "metadata": {
634 | "application/vnd.databricks.v1+cell": {
635 | "inputWidgets": {},
636 | "nuid": "3945e9c8-fc53-44c5-995b-3f1dc22874c2",
637 | "showTitle": false,
638 | "title": ""
639 | }
640 | },
641 | "source": [
642 | "**List Comprehension with if Clause**\n",
643 | "\n",
644 | "A list comprehension may have an optional associated if clause to filter items out of the result. Iterable’s items are skipped for which the if clause is not true."
645 | ]
646 | },
647 | {
648 | "cell_type": "code",
649 | "execution_count": 15,
650 | "metadata": {
651 | "application/vnd.databricks.v1+cell": {
652 | "inputWidgets": {},
653 | "nuid": "3a97ba94-4fc4-4500-8839-9ac606095bfd",
654 | "showTitle": false,
655 | "title": ""
656 | }
657 | },
658 | "outputs": [
659 | {
660 | "name": "stdout",
661 | "output_type": "stream",
662 | "text": [
663 | "[0, 2, 4]\n"
664 | ]
665 | }
666 | ],
667 | "source": [
668 | "# Filter list to exclude negative numbers\n",
669 | "vec = [-4, -2, 0, 2, 4]\n",
670 | "L = [x for x in vec if x >= 0]\n",
671 | "print(L)"
672 | ]
673 | },
674 | {
675 | "cell_type": "code",
676 | "execution_count": 16,
677 | "metadata": {
678 | "application/vnd.databricks.v1+cell": {
679 | "inputWidgets": {},
680 | "nuid": "a2cba93a-4832-4311-bad3-d896dde0f47a",
681 | "showTitle": false,
682 | "title": ""
683 | }
684 | },
685 | "outputs": [
686 | {
687 | "name": "stdout",
688 | "output_type": "stream",
689 | "text": [
690 | "[0, 2, 4]\n"
691 | ]
692 | }
693 | ],
694 | "source": [
695 | "# Without list comprehension\n",
696 | "vec = [-4, -2, 0, 2, 4]\n",
697 | "L = []\n",
698 | "for x in vec:\n",
699 | " if x >= 0:\n",
700 | " L.append(x)\n",
701 | "print(L)"
702 | ]
703 | },
704 | {
705 | "cell_type": "markdown",
706 | "metadata": {
707 | "application/vnd.databricks.v1+cell": {
708 | "inputWidgets": {},
709 | "nuid": "51128456-09b3-4175-9387-67f7d6a7c5ed",
710 | "showTitle": false,
711 | "title": ""
712 | }
713 | },
714 | "source": [
715 | "**Nested List Comprehensions**\n",
716 | "\n",
717 | "The initial expression in a list comprehension can be any expression, including another list comprehension.\n",
718 | "\n",
719 | "
"
720 | ]
721 | },
722 | {
723 | "cell_type": "code",
724 | "execution_count": 17,
725 | "metadata": {
726 | "application/vnd.databricks.v1+cell": {
727 | "inputWidgets": {},
728 | "nuid": "94b80a6f-9833-4662-874d-33ecc4bb6112",
729 | "showTitle": false,
730 | "title": ""
731 | }
732 | },
733 | "outputs": [
734 | {
735 | "name": "stdout",
736 | "output_type": "stream",
737 | "text": [
738 | "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
739 | ]
740 | }
741 | ],
742 | "source": [
743 | "# With list comprehension\n",
744 | "vector = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
745 | "L = [number for x in vector for number in x]\n",
746 | "print(L)"
747 | ]
748 | },
749 | {
750 | "cell_type": "code",
751 | "execution_count": 18,
752 | "metadata": {
753 | "application/vnd.databricks.v1+cell": {
754 | "inputWidgets": {},
755 | "nuid": "4e49a38e-2c2b-4585-bc73-b55193b9bfb1",
756 | "showTitle": false,
757 | "title": ""
758 | }
759 | },
760 | "outputs": [
761 | {
762 | "name": "stdout",
763 | "output_type": "stream",
764 | "text": [
765 | "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
766 | ]
767 | }
768 | ],
769 | "source": [
770 | "# Equivalent to the following plain, old nested loop:\n",
771 | "vector = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
772 | "L = []\n",
773 | "for x in vector:\n",
774 | " for number in x:\n",
775 | " L.append(number)\n",
776 | "print(L)"
777 | ]
778 | },
779 | {
780 | "cell_type": "code",
781 | "execution_count": 19,
782 | "metadata": {
783 | "application/vnd.databricks.v1+cell": {
784 | "inputWidgets": {},
785 | "nuid": "b89320a4-c20e-49f0-8d58-d95f9850b72a",
786 | "showTitle": false,
787 | "title": ""
788 | }
789 | },
790 | "outputs": [
791 | {
792 | "data": {
793 | "text/plain": [
794 | "[[1, 4, 7], [2, 5, 8], [3, 6, 9]]"
795 | ]
796 | },
797 | "execution_count": 19,
798 | "metadata": {},
799 | "output_type": "execute_result"
800 | }
801 | ],
802 | "source": [
803 | "matrix = [[1, 2, 3],\n",
804 | " [4, 5, 6],\n",
805 | " [7, 8, 9]]\n",
806 | "L = [[row[i] for row in matrix] for i in range(3)]\n",
807 | "L"
808 | ]
809 | },
810 | {
811 | "cell_type": "markdown",
812 | "metadata": {
813 | "application/vnd.databricks.v1+cell": {
814 | "inputWidgets": {},
815 | "nuid": "479c4974-62bd-49f5-857d-25c905792afe",
816 | "showTitle": false,
817 | "title": ""
818 | }
819 | },
820 | "source": [
821 | "**List Comprehension vs map() + lambda**\n",
822 | "\n",
823 | "When all you’re doing is calling an already-defined function on each element, map(f, L) is a little faster than the corresponding list comprehension [f(x) for x in L]. Following example collects the ASCII codes of all characters in an entire string."
824 | ]
825 | },
826 | {
827 | "cell_type": "code",
828 | "execution_count": 20,
829 | "metadata": {
830 | "application/vnd.databricks.v1+cell": {
831 | "inputWidgets": {},
832 | "nuid": "2fa0b8c0-7331-447c-b514-e9903e3beade",
833 | "showTitle": false,
834 | "title": ""
835 | }
836 | },
837 | "outputs": [
838 | {
839 | "name": "stdout",
840 | "output_type": "stream",
841 | "text": [
842 | "[102, 111, 111]\n",
843 | "[102, 111, 111]\n"
844 | ]
845 | }
846 | ],
847 | "source": [
848 | "# With list comprehension\n",
849 | "L = [ord(x) for x in 'foo']\n",
850 | "print(L)\n",
851 | "\n",
852 | "# With map() function\n",
853 | "list(map(ord, 'foo'))\n",
854 | "print(L)"
855 | ]
856 | },
857 | {
858 | "cell_type": "markdown",
859 | "metadata": {
860 | "application/vnd.databricks.v1+cell": {
861 | "inputWidgets": {},
862 | "nuid": "6b7f08cd-d1ca-4b8d-9279-cbea081034b6",
863 | "showTitle": false,
864 | "title": ""
865 | }
866 | },
867 | "source": [
868 | "What is `lambda` in python?\n",
869 | "\n",
870 | "A lambda function is a small anonymous function.It can take any number of arguments, but can only have one expression."
871 | ]
872 | },
873 | {
874 | "cell_type": "code",
875 | "execution_count": 21,
876 | "metadata": {
877 | "application/vnd.databricks.v1+cell": {
878 | "inputWidgets": {},
879 | "nuid": "19f4a275-de92-4b9f-87e9-72321dbe3cf9",
880 | "showTitle": false,
881 | "title": ""
882 | }
883 | },
884 | "outputs": [
885 | {
886 | "name": "stdout",
887 | "output_type": "stream",
888 | "text": [
889 | "15\n"
890 | ]
891 | }
892 | ],
893 | "source": [
894 | "x = lambda a : a + 10\n",
895 | "print(x(5))"
896 | ]
897 | },
898 | {
899 | "cell_type": "code",
900 | "execution_count": 22,
901 | "metadata": {
902 | "application/vnd.databricks.v1+cell": {
903 | "inputWidgets": {},
904 | "nuid": "f36bb781-9f5d-4198-b3f0-ebdc31692589",
905 | "showTitle": false,
906 | "title": ""
907 | }
908 | },
909 | "outputs": [
910 | {
911 | "name": "stdout",
912 | "output_type": "stream",
913 | "text": [
914 | "30\n"
915 | ]
916 | }
917 | ],
918 | "source": [
919 | "x = lambda a, b : a * b\n",
920 | "print(x(5, 6))"
921 | ]
922 | },
923 | {
924 | "cell_type": "markdown",
925 | "metadata": {
926 | "application/vnd.databricks.v1+cell": {
927 | "inputWidgets": {},
928 | "nuid": "f61b13fc-d0c0-4a8e-92ed-92a41ec5e1a6",
929 | "showTitle": false,
930 | "title": ""
931 | }
932 | },
933 | "source": [
934 | "However, when evaluating any other expression, `[some_expr for x in L]` is faster and clearer than `map(lambda x: some_expr, L)`, because the map incurs an extra function call for each element. Following example creates a list of all integer square numbers."
935 | ]
936 | },
937 | {
938 | "cell_type": "code",
939 | "execution_count": 23,
940 | "metadata": {
941 | "application/vnd.databricks.v1+cell": {
942 | "inputWidgets": {},
943 | "nuid": "28dc1540-0d43-4a2d-b7e4-86023ad53f4a",
944 | "showTitle": false,
945 | "title": ""
946 | }
947 | },
948 | "outputs": [
949 | {
950 | "name": "stdout",
951 | "output_type": "stream",
952 | "text": [
953 | "[0, 2, 4, 6, 8]\n",
954 | "[0, 2, 4, 6, 8]\n"
955 | ]
956 | }
957 | ],
958 | "source": [
959 | "L = [x for x in range(10) if x % 2 == 0]\n",
960 | "print(L)\n",
961 | "\n",
962 | "# With filter() function\n",
963 | "L = list(filter((lambda x: x % 2 == 0), range(10)))\n",
964 | "print(L)"
965 | ]
966 | },
967 | {
968 | "cell_type": "markdown",
969 | "metadata": {
970 | "application/vnd.databricks.v1+cell": {
971 | "inputWidgets": {},
972 | "nuid": "9a4c9ce8-d732-4eb2-bc98-f58a9b212653",
973 | "showTitle": false,
974 | "title": ""
975 | }
976 | },
977 | "source": [
978 | "**Dictionary Comprehension**\n",
979 | "\n",
980 | "The idea of comprehension is not just unique to lists in Python. Dictionaries also have comprehensions."
981 | ]
982 | },
983 | {
984 | "cell_type": "code",
985 | "execution_count": 24,
986 | "metadata": {
987 | "application/vnd.databricks.v1+cell": {
988 | "inputWidgets": {},
989 | "nuid": "ad3c82f7-37c4-44c4-b20d-ba0b5f766198",
990 | "showTitle": false,
991 | "title": ""
992 | }
993 | },
994 | "outputs": [
995 | {
996 | "name": "stdout",
997 | "output_type": "stream",
998 | "text": [
999 | "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n"
1000 | ]
1001 | }
1002 | ],
1003 | "source": [
1004 | "D = {}\n",
1005 | "for x in range(5):\n",
1006 | " D[x] = x**2\n",
1007 | "\n",
1008 | "print(D)"
1009 | ]
1010 | },
1011 | {
1012 | "cell_type": "markdown",
1013 | "metadata": {
1014 | "application/vnd.databricks.v1+cell": {
1015 | "inputWidgets": {},
1016 | "nuid": "2a1f800e-9265-4dc7-b26d-385ec8b0a5fd",
1017 | "showTitle": false,
1018 | "title": ""
1019 | }
1020 | },
1021 | "source": [
1022 | "The general syntax for a dictionary comprehension is:\n",
1023 | "\n",
1024 | "
"
1025 | ]
1026 | },
1027 | {
1028 | "cell_type": "code",
1029 | "execution_count": 25,
1030 | "metadata": {
1031 | "application/vnd.databricks.v1+cell": {
1032 | "inputWidgets": {},
1033 | "nuid": "518d439d-fc15-4f63-9662-6466dd86b613",
1034 | "showTitle": false,
1035 | "title": ""
1036 | }
1037 | },
1038 | "outputs": [
1039 | {
1040 | "name": "stdout",
1041 | "output_type": "stream",
1042 | "text": [
1043 | "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n"
1044 | ]
1045 | }
1046 | ],
1047 | "source": [
1048 | "D = {x: x**2 for x in range(5)}\n",
1049 | "print(D)"
1050 | ]
1051 | },
1052 | {
1053 | "cell_type": "code",
1054 | "execution_count": 26,
1055 | "metadata": {
1056 | "application/vnd.databricks.v1+cell": {
1057 | "inputWidgets": {},
1058 | "nuid": "4f1efee4-e709-454f-a1ec-a8540c621bc5",
1059 | "showTitle": false,
1060 | "title": ""
1061 | }
1062 | },
1063 | "outputs": [
1064 | {
1065 | "name": "stdout",
1066 | "output_type": "stream",
1067 | "text": [
1068 | "{'red': 'RED', 'green': 'GREEN', 'blue': 'BLUE'}\n"
1069 | ]
1070 | }
1071 | ],
1072 | "source": [
1073 | "L = ['ReD', 'GrEeN', 'BlUe']\n",
1074 | "D = {c.lower(): c.upper() for c in L}\n",
1075 | "print(D)"
1076 | ]
1077 | }
1078 | ],
1079 | "metadata": {
1080 | "anaconda-cloud": {},
1081 | "application/vnd.databricks.v1+notebook": {
1082 | "dashboards": [],
1083 | "language": "python",
1084 | "notebookMetadata": {
1085 | "pythonIndentUnit": 2
1086 | },
1087 | "notebookName": "Python_Part2",
1088 | "notebookOrigID": 2425280650113424,
1089 | "widgets": {}
1090 | },
1091 | "kernelspec": {
1092 | "display_name": "Python 3",
1093 | "language": "python",
1094 | "name": "python3"
1095 | },
1096 | "language_info": {
1097 | "codemirror_mode": {
1098 | "name": "ipython",
1099 | "version": 3
1100 | },
1101 | "file_extension": ".py",
1102 | "mimetype": "text/x-python",
1103 | "name": "python",
1104 | "nbconvert_exporter": "python",
1105 | "pygments_lexer": "ipython3",
1106 | "version": "3.7.3"
1107 | }
1108 | },
1109 | "nbformat": 4,
1110 | "nbformat_minor": 1
1111 | }
1112 |
--------------------------------------------------------------------------------
/Python/Python_Part4.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Python for Data Science and Machine Learning - Part 4\n",
8 | "\n",
9 | "----"
10 | ]
11 | },
12 | {
13 | "cell_type": "markdown",
14 | "metadata": {
15 | "application/vnd.databricks.v1+cell": {
16 | "inputWidgets": {},
17 | "nuid": "3e89c394-8864-4974-b446-278c1ab29799",
18 | "showTitle": false,
19 | "title": ""
20 | }
21 | },
22 | "source": [
23 | "## Object-Oriented Programming (OOP) in Python"
24 | ]
25 | },
26 | {
27 | "cell_type": "markdown",
28 | "metadata": {
29 | "application/vnd.databricks.v1+cell": {
30 | "inputWidgets": {},
31 | "nuid": "7bf68754-ac3e-4f3c-abbc-9f20cd8f06ca",
32 | "showTitle": false,
33 | "title": ""
34 | }
35 | },
36 | "source": [
37 | "Object-oriented programming is a programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects. In simple words, It is used to structure a software program into simple, reusable pieces of code blueprints (usually called classes), which are used to create individual instances of objects."
38 | ]
39 | },
40 | {
41 | "cell_type": "markdown",
42 | "metadata": {
43 | "application/vnd.databricks.v1+cell": {
44 | "inputWidgets": {},
45 | "nuid": "6115538b-1aee-4fea-8fa2-f80cd98b6acf",
46 | "showTitle": false,
47 | "title": ""
48 | }
49 | },
50 | "source": [
51 | "## Classes and Objects\n",
52 | "\n",
53 | "Classes and objects are the two main aspects of object-oriented programming.\n",
54 | "\n",
55 | "A class is the blueprint from which individual objects are created. In the real world, for example, there may be thousands of cars in existence, all of the same make and model.\n",
56 | "\n",
57 | "
\n",
58 | "\n",
59 | "Each car was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your car is an instance (object) of the class Car."
60 | ]
61 | },
62 | {
63 | "cell_type": "markdown",
64 | "metadata": {
65 | "application/vnd.databricks.v1+cell": {
66 | "inputWidgets": {},
67 | "nuid": "5111a653-45b5-4142-946e-c26a43eb4e87",
68 | "showTitle": false,
69 | "title": ""
70 | }
71 | },
72 | "source": [
73 | "**Create a Class**\n",
74 | "\n",
75 | "To create a custom object in Python, a class has to be defined first using the keyword `class`. For example, if we want to create objects to represent information about cars, first we will need to define a class called Car."
76 | ]
77 | },
78 | {
79 | "cell_type": "code",
80 | "execution_count": 0,
81 | "metadata": {
82 | "application/vnd.databricks.v1+cell": {
83 | "inputWidgets": {},
84 | "nuid": "b4c122ba-799b-4527-9de3-efbfb54ed5bc",
85 | "showTitle": false,
86 | "title": ""
87 | }
88 | },
89 | "outputs": [],
90 | "source": [
91 | "class Car:\n",
92 | " pass"
93 | ]
94 | },
95 | {
96 | "cell_type": "markdown",
97 | "metadata": {
98 | "application/vnd.databricks.v1+cell": {
99 | "inputWidgets": {},
100 | "nuid": "ee1f191a-3b68-4c41-9013-fb3ca88b8dba",
101 | "showTitle": false,
102 | "title": ""
103 | }
104 | },
105 | "source": [
106 | "**The `__init__()` Method**\n",
107 | "\n",
108 | "`__init__()` is the special method that initializes an individual object. This method runs automatically each time an object of a class is created and tells python what the initial __state__ (that is, the initial values of the object’s\n",
109 | "properties) of the object should be."
110 | ]
111 | },
112 | {
113 | "cell_type": "code",
114 | "execution_count": 0,
115 | "metadata": {
116 | "application/vnd.databricks.v1+cell": {
117 | "inputWidgets": {},
118 | "nuid": "9e329951-006c-4126-8798-f3dd6a434776",
119 | "showTitle": false,
120 | "title": ""
121 | }
122 | },
123 | "outputs": [],
124 | "source": [
125 | "class Car:\n",
126 | " \n",
127 | " # initializer\n",
128 | " def __init__(self):\n",
129 | " pass"
130 | ]
131 | },
132 | {
133 | "cell_type": "markdown",
134 | "metadata": {
135 | "application/vnd.databricks.v1+cell": {
136 | "inputWidgets": {},
137 | "nuid": "4d429297-0d13-4cbf-a9c5-7c849f9d112e",
138 | "showTitle": false,
139 | "title": ""
140 | }
141 | },
142 | "source": [
143 | "**The self parameter**\n",
144 | "\n",
145 | "The `self` parameter refers to the individual object itself. It is used to fetch or set attributes of the particular instance. This parameter doesn’t have to be called `self`, you can call it whatever you want, but it is standard practice, and you should probably stick with it."
146 | ]
147 | },
148 | {
149 | "cell_type": "markdown",
150 | "metadata": {
151 | "application/vnd.databricks.v1+cell": {
152 | "inputWidgets": {},
153 | "nuid": "9aec7332-f72a-4923-973a-7007ea931bf4",
154 | "showTitle": false,
155 | "title": ""
156 | }
157 | },
158 | "source": [
159 | "**Attributes**\n",
160 | "\n",
161 | "Every class you write in Python has two basic features: attributes and methods.\n",
162 | "\n",
163 | "Attributes are the individual things that differentiate one object from another. They determine the appearance, state, or other qualities of that object.\n",
164 | "\n",
165 | "In our case, the 'Car' class might have the following attributes:\n",
166 | "\n",
167 | "- Style: Sedan, SUV, Coupe\n",
168 | "- Color: Silver, Black, White\n",
169 | "- Wheels: Four\n",
170 | "\n",
171 | "There are two types of attributes: instance attributes and class attributes"
172 | ]
173 | },
174 | {
175 | "cell_type": "markdown",
176 | "metadata": {
177 | "application/vnd.databricks.v1+cell": {
178 | "inputWidgets": {},
179 | "nuid": "6ee76a85-b4ca-4f2c-a0fd-140d3f381e11",
180 | "showTitle": false,
181 | "title": ""
182 | }
183 | },
184 | "source": [
185 | "**Instance Attributes**\n",
186 | "\n",
187 | "The instance attribute is a variable that is unique to each object (instance). Every object of that class has its own copy of that variable. Any changes made to the variable don’t reflect in other objects of that class.\n",
188 | "\n",
189 | "After the self argument, we can specify any other arguments required to create an instance of the class.The following updated definition of the Car() class shows how to write an `.__init__()` method that creates two instance attributes: .color and .style. Each car has a specific color and style."
190 | ]
191 | },
192 | {
193 | "cell_type": "code",
194 | "execution_count": 0,
195 | "metadata": {
196 | "application/vnd.databricks.v1+cell": {
197 | "inputWidgets": {},
198 | "nuid": "227b6086-c835-4a4d-9426-998c8dde706d",
199 | "showTitle": false,
200 | "title": ""
201 | }
202 | },
203 | "outputs": [],
204 | "source": [
205 | "# A class with two instance attributes\n",
206 | "class Car:\n",
207 | "\n",
208 | " # initializer with instance attributes\n",
209 | " def __init__(self, color, style):\n",
210 | " self.color = color\n",
211 | " self.style = style"
212 | ]
213 | },
214 | {
215 | "cell_type": "markdown",
216 | "metadata": {
217 | "application/vnd.databricks.v1+cell": {
218 | "inputWidgets": {},
219 | "nuid": "732c2e62-96fc-4daa-9c6d-bde9c374749c",
220 | "showTitle": false,
221 | "title": ""
222 | }
223 | },
224 | "source": [
225 | "**Class Attribute**\n",
226 | "\n",
227 | "The class attribute is a variable that is same for all objects. And there’s only one copy of that variable that is shared with all objects. Any changes made to that variable will reflect in all other objects.\n",
228 | "\n",
229 | "In the case of our Car() class, each car has 4 wheels. So while each car has a unique style and color, every car will have 4 wheels."
230 | ]
231 | },
232 | {
233 | "cell_type": "code",
234 | "execution_count": 0,
235 | "metadata": {
236 | "application/vnd.databricks.v1+cell": {
237 | "inputWidgets": {},
238 | "nuid": "0c26de4c-b158-4613-ad08-e68bb17676b3",
239 | "showTitle": false,
240 | "title": ""
241 | }
242 | },
243 | "outputs": [],
244 | "source": [
245 | "# A class with one class attribute\n",
246 | "class Car:\n",
247 | "\n",
248 | " # class attribute\n",
249 | " wheels = 4\n",
250 | "\n",
251 | " # initializer with instance attributes\n",
252 | " def __init__(self, color, style):\n",
253 | " self.color = color\n",
254 | " self.style = style"
255 | ]
256 | },
257 | {
258 | "cell_type": "markdown",
259 | "metadata": {
260 | "application/vnd.databricks.v1+cell": {
261 | "inputWidgets": {},
262 | "nuid": "40aee567-e9c6-40ab-8d1c-22dd755f49a9",
263 | "showTitle": false,
264 | "title": ""
265 | }
266 | },
267 | "source": [
268 | "**Create/Instantiate an Object**\n",
269 | "\n",
270 | "Once a class has been defined, you have a blueprint for creating—also known as instantiating—new objects."
271 | ]
272 | },
273 | {
274 | "cell_type": "code",
275 | "execution_count": 0,
276 | "metadata": {
277 | "application/vnd.databricks.v1+cell": {
278 | "inputWidgets": {},
279 | "nuid": "d74f15d5-b52b-457d-a26f-76fa7066354e",
280 | "showTitle": false,
281 | "title": ""
282 | }
283 | },
284 | "outputs": [],
285 | "source": [
286 | "c = Car('Black','Sedan')"
287 | ]
288 | },
289 | {
290 | "cell_type": "markdown",
291 | "metadata": {
292 | "application/vnd.databricks.v1+cell": {
293 | "inputWidgets": {},
294 | "nuid": "e79af579-6c63-49e9-98c3-5385d3dce769",
295 | "showTitle": false,
296 | "title": ""
297 | }
298 | },
299 | "source": [
300 | "Here, we created a new object from the Car class by passing strings for the style and color parameters. But, we didn’t pass in the self argument.\n",
301 | "\n",
302 | "This is because, when you create a new object, Python automatically determines what self is (our newly-created object in this case) and passes it to the __init__ method."
303 | ]
304 | },
305 | {
306 | "cell_type": "markdown",
307 | "metadata": {
308 | "application/vnd.databricks.v1+cell": {
309 | "inputWidgets": {},
310 | "nuid": "6fa8bfd5-c738-4702-9408-c08786fe6b98",
311 | "showTitle": false,
312 | "title": ""
313 | }
314 | },
315 | "source": [
316 | "**Access and Modify Attributes**"
317 | ]
318 | },
319 | {
320 | "cell_type": "code",
321 | "execution_count": 0,
322 | "metadata": {
323 | "application/vnd.databricks.v1+cell": {
324 | "inputWidgets": {},
325 | "nuid": "b7997598-f2df-4166-8196-f1fcd69a354d",
326 | "showTitle": false,
327 | "title": ""
328 | }
329 | },
330 | "outputs": [
331 | {
332 | "data": {
333 | "text/plain": [
334 | "Sedan\n",
335 | "Black\n",
336 | "SUV\n"
337 | ]
338 | },
339 | "metadata": {
340 | "application/vnd.databricks.v1+output": {
341 | "addedWidgets": {},
342 | "arguments": {},
343 | "data": "Sedan\nBlack\nSUV\n",
344 | "datasetInfos": [],
345 | "metadata": {},
346 | "removedWidgets": [],
347 | "type": "ansi"
348 | }
349 | },
350 | "output_type": "display_data"
351 | }
352 | ],
353 | "source": [
354 | "# Access attributes\n",
355 | "print(c.style)\n",
356 | "# Prints Sedan\n",
357 | "print(c.color)\n",
358 | "# Prints Black\n",
359 | "\n",
360 | "# Modify attribute\n",
361 | "c.style = 'SUV'\n",
362 | "print(c.style)\n",
363 | "# Prints SUV"
364 | ]
365 | },
366 | {
367 | "cell_type": "markdown",
368 | "metadata": {
369 | "application/vnd.databricks.v1+cell": {
370 | "inputWidgets": {},
371 | "nuid": "58d6bed5-0ba2-4d87-bbdf-c3527c2c92b8",
372 | "showTitle": false,
373 | "title": ""
374 | }
375 | },
376 | "source": [
377 | "**Methods**\n",
378 | "\n",
379 | "Methods determine what type of functionality a class has, how it handles its data, and its overall behavior. Without methods, a class would simply be a structure.\n",
380 | "\n",
381 | "In our case, the ‘Car’ class might have the following methods:\n",
382 | "\n",
383 | "- Change color\n",
384 | "- Start engine\n",
385 | "- Stop engine\n",
386 | "- Change gear\n",
387 | "\n",
388 | "Just like `.__init__()`, the first argument of an instance method is always `self`:"
389 | ]
390 | },
391 | {
392 | "cell_type": "code",
393 | "execution_count": 0,
394 | "metadata": {
395 | "application/vnd.databricks.v1+cell": {
396 | "inputWidgets": {},
397 | "nuid": "1edb6f16-061b-41d9-b188-1cf58368f74f",
398 | "showTitle": false,
399 | "title": ""
400 | }
401 | },
402 | "outputs": [
403 | {
404 | "data": {
405 | "text/plain": [
406 | "This car is a Black Sedan\n",
407 | "This car is a White Sedan\n"
408 | ]
409 | },
410 | "metadata": {
411 | "application/vnd.databricks.v1+output": {
412 | "addedWidgets": {},
413 | "arguments": {},
414 | "data": "This car is a Black Sedan\nThis car is a White Sedan\n",
415 | "datasetInfos": [],
416 | "metadata": {},
417 | "removedWidgets": [],
418 | "type": "ansi"
419 | }
420 | },
421 | "output_type": "display_data"
422 | }
423 | ],
424 | "source": [
425 | "class Car:\n",
426 | "\n",
427 | " # class attribute\n",
428 | " wheels = 4\n",
429 | "\n",
430 | " # initializer / instance attributes\n",
431 | " def __init__(self, color, style):\n",
432 | " self.color = color\n",
433 | " self.style = style\n",
434 | "\n",
435 | " # method 1\n",
436 | " def showDescription(self):\n",
437 | " print(\"This car is a\", self.color, self.style)\n",
438 | "\n",
439 | " # method 2\n",
440 | " def changeColor(self, color):\n",
441 | " self.color = color\n",
442 | "\n",
443 | "c = Car('Black', 'Sedan')\n",
444 | "\n",
445 | "# call method 1\n",
446 | "c.showDescription()\n",
447 | "# Prints This car is a Black Sedan\n",
448 | "\n",
449 | "# call method 2 and set color\n",
450 | "c.changeColor('White')\n",
451 | "\n",
452 | "c.showDescription()\n",
453 | "# Prints This car is a White Sedan"
454 | ]
455 | },
456 | {
457 | "cell_type": "markdown",
458 | "metadata": {
459 | "application/vnd.databricks.v1+cell": {
460 | "inputWidgets": {},
461 | "nuid": "e020f25d-8240-45cb-8b86-0590d5212e8f",
462 | "showTitle": false,
463 | "title": ""
464 | }
465 | },
466 | "source": [
467 | "Another example"
468 | ]
469 | },
470 | {
471 | "cell_type": "code",
472 | "execution_count": 0,
473 | "metadata": {
474 | "application/vnd.databricks.v1+cell": {
475 | "inputWidgets": {},
476 | "nuid": "78f7525e-cf4b-4101-97ad-1ab705255e65",
477 | "showTitle": false,
478 | "title": ""
479 | }
480 | },
481 | "outputs": [
482 | {
483 | "data": {
484 | "text/plain": [
485 | "Miles 4\n"
486 | ]
487 | },
488 | "metadata": {
489 | "application/vnd.databricks.v1+output": {
490 | "addedWidgets": {},
491 | "arguments": {},
492 | "data": "Miles 4\n",
493 | "datasetInfos": [],
494 | "metadata": {},
495 | "removedWidgets": [],
496 | "type": "ansi"
497 | }
498 | },
499 | "output_type": "display_data"
500 | },
501 | {
502 | "data": {
503 | "text/plain": [
504 | "Out[8]: 'Miles is 4 years old'"
505 | ]
506 | },
507 | "metadata": {
508 | "application/vnd.databricks.v1+output": {
509 | "addedWidgets": {},
510 | "arguments": {},
511 | "data": "Out[8]: 'Miles is 4 years old'",
512 | "datasetInfos": [],
513 | "metadata": {},
514 | "removedWidgets": [],
515 | "type": "ansi"
516 | }
517 | },
518 | "output_type": "display_data"
519 | }
520 | ],
521 | "source": [
522 | "class Dog:\n",
523 | " species = 'Canis familaris'\n",
524 | " \n",
525 | " def __init__(self,name,age):\n",
526 | " self.name = name\n",
527 | " self.age = age\n",
528 | "\n",
529 | " # instance method\n",
530 | " def description(self):\n",
531 | " return f\"{self.name} is {self.age} years old\"\n",
532 | " \n",
533 | " # another instance\n",
534 | " def speak(self, sound):\n",
535 | " return f\"{self.name} says {sound}\"\n",
536 | "\n",
537 | "miles = Dog('Miles',4)\n",
538 | "print (miles.name, miles.age)\n",
539 | "\n",
540 | "miles.description()"
541 | ]
542 | },
543 | {
544 | "cell_type": "code",
545 | "execution_count": 0,
546 | "metadata": {
547 | "application/vnd.databricks.v1+cell": {
548 | "inputWidgets": {},
549 | "nuid": "d1161572-c046-4a3a-b55d-894a4e301ad8",
550 | "showTitle": false,
551 | "title": ""
552 | }
553 | },
554 | "outputs": [
555 | {
556 | "data": {
557 | "text/plain": [
558 | "Out[9]: 'Miles says Woof Woof'"
559 | ]
560 | },
561 | "metadata": {
562 | "application/vnd.databricks.v1+output": {
563 | "addedWidgets": {},
564 | "arguments": {},
565 | "data": "Out[9]: 'Miles says Woof Woof'",
566 | "datasetInfos": [],
567 | "metadata": {},
568 | "removedWidgets": [],
569 | "type": "ansi"
570 | }
571 | },
572 | "output_type": "display_data"
573 | }
574 | ],
575 | "source": [
576 | "miles.speak(\"Woof Woof\")"
577 | ]
578 | },
579 | {
580 | "cell_type": "markdown",
581 | "metadata": {
582 | "application/vnd.databricks.v1+cell": {
583 | "inputWidgets": {},
584 | "nuid": "66a688e5-e46c-45c3-bae0-8bd3c421442f",
585 | "showTitle": false,
586 | "title": ""
587 | }
588 | },
589 | "source": [
590 | "## Inheritance from other classes\n",
591 | "\n",
592 | "Inheritance is the process by which one class takes takes on the attribute and methods of another. Newly formed classes are called **child or derived classes**, and the classes that child classes are derived from are called **parent classes**. Putting it simply, inheritance is the process of creating a new class from an existing one.\n",
593 | "\n",
594 | "Child classes can override and extend the attributes and methods of parent classes. In other words, child classes inherit all of the parent’s attributes and methods but can also specify different attributes and methods that are unique to themselves, or even redefine methods from their parent class."
595 | ]
596 | },
597 | {
598 | "cell_type": "markdown",
599 | "metadata": {
600 | "application/vnd.databricks.v1+cell": {
601 | "inputWidgets": {},
602 | "nuid": "625de21d-26a1-4b62-8c4e-750966ce5a52",
603 | "showTitle": false,
604 | "title": ""
605 | }
606 | },
607 | "source": [
608 | "**Analogy**\n",
609 | "\n",
610 | "There exists a hierarchy relationship between classes. It’s similar to relationships that you know from real life.\n",
611 | "\n",
612 | "Think about vehicles, for example. Bikes, cars, buses and trucks, all share the characteristics of vehicles (speed, color, gear). Yet each has additional features that make them different.\n",
613 | "\n",
614 | "Keeping that in mind, you could implement a Vehicle (as a base) class in Python. Whereas, Cars, Buses and Trucks and Bikes can be implemented as subclasses which will inherit from vehicle.\n",
615 | "\n",
616 | "
"
617 | ]
618 | },
619 | {
620 | "cell_type": "markdown",
621 | "metadata": {
622 | "application/vnd.databricks.v1+cell": {
623 | "inputWidgets": {},
624 | "nuid": "ec3519d4-995c-4304-bd8e-fdc16b2c58dd",
625 | "showTitle": false,
626 | "title": ""
627 | }
628 | },
629 | "source": [
630 | "**Defining a Base/Parent Class**\n",
631 | "\n",
632 | "Any class that does not inherit from another class is known as a **base/parent class**.\n",
633 | "\n",
634 | "The example below defines a base class called Vehicle. It has a method called description that prints the description of the vehicle."
635 | ]
636 | },
637 | {
638 | "cell_type": "code",
639 | "execution_count": 0,
640 | "metadata": {
641 | "application/vnd.databricks.v1+cell": {
642 | "inputWidgets": {},
643 | "nuid": "cf2940ed-db5f-425d-b534-b54ea4c262bb",
644 | "showTitle": false,
645 | "title": ""
646 | }
647 | },
648 | "outputs": [],
649 | "source": [
650 | "# base class\n",
651 | "class Vehicle():\n",
652 | " def description(self):\n",
653 | " print(\"I'm a Vehicle!\")"
654 | ]
655 | },
656 | {
657 | "cell_type": "markdown",
658 | "metadata": {
659 | "application/vnd.databricks.v1+cell": {
660 | "inputWidgets": {},
661 | "nuid": "46b457d2-12a8-4179-9144-519455ab4e69",
662 | "showTitle": false,
663 | "title": ""
664 | }
665 | },
666 | "source": [
667 | "**Subclassing**\n",
668 | "\n",
669 | "The act of basing a new class on an existing class is known as Subclassing. It allows you to add new functionality or override existing functionality."
670 | ]
671 | },
672 | {
673 | "cell_type": "code",
674 | "execution_count": 0,
675 | "metadata": {
676 | "application/vnd.databricks.v1+cell": {
677 | "inputWidgets": {},
678 | "nuid": "8a35b2ae-5b39-4b26-adc0-6cc140999aee",
679 | "showTitle": false,
680 | "title": ""
681 | }
682 | },
683 | "outputs": [],
684 | "source": [
685 | "# base class\n",
686 | "class Vehicle():\n",
687 | " def description(self):\n",
688 | " print(\"I'm a Vehicle!\")\n",
689 | "\n",
690 | "# subclass/child class\n",
691 | "class Car(Vehicle):\n",
692 | " pass"
693 | ]
694 | },
695 | {
696 | "cell_type": "code",
697 | "execution_count": 0,
698 | "metadata": {
699 | "application/vnd.databricks.v1+cell": {
700 | "inputWidgets": {},
701 | "nuid": "0ee6638f-fee8-4d6d-8981-cb4c1ee099a5",
702 | "showTitle": false,
703 | "title": ""
704 | }
705 | },
706 | "outputs": [
707 | {
708 | "data": {
709 | "text/plain": [
710 | "I'm a Vehicle!\n",
711 | "I'm a Vehicle!\n"
712 | ]
713 | },
714 | "metadata": {
715 | "application/vnd.databricks.v1+output": {
716 | "addedWidgets": {},
717 | "arguments": {},
718 | "data": "I'm a Vehicle!\nI'm a Vehicle!\n",
719 | "datasetInfos": [],
720 | "metadata": {},
721 | "removedWidgets": [],
722 | "type": "ansi"
723 | }
724 | },
725 | "output_type": "display_data"
726 | }
727 | ],
728 | "source": [
729 | "# base class\n",
730 | "class Vehicle():\n",
731 | " def description(self):\n",
732 | " print(\"I'm a Vehicle!\")\n",
733 | "\n",
734 | "# subclass\n",
735 | "class Car(Vehicle):\n",
736 | " pass\n",
737 | "\n",
738 | "# create an object from each class\n",
739 | "v = Vehicle()\n",
740 | "c = Car()\n",
741 | "\n",
742 | "v.description()\n",
743 | "# Prints I'm a Vehicle!\n",
744 | "c.description()\n",
745 | "# Prints I'm a Vehicle!"
746 | ]
747 | },
748 | {
749 | "cell_type": "markdown",
750 | "metadata": {
751 | "application/vnd.databricks.v1+cell": {
752 | "inputWidgets": {},
753 | "nuid": "34590809-02eb-4279-b43f-ce89c483078c",
754 | "showTitle": false,
755 | "title": ""
756 | }
757 | },
758 | "source": [
759 | "**Override a Method**\n",
760 | "\n",
761 | "A Car class inherited everything from its base class Vehicle. However, a subclass should be different from its base class in some way; otherwise, there’s no point in defining a new class."
762 | ]
763 | },
764 | {
765 | "cell_type": "code",
766 | "execution_count": 0,
767 | "metadata": {
768 | "application/vnd.databricks.v1+cell": {
769 | "inputWidgets": {},
770 | "nuid": "29bbae17-a2b7-447c-93ff-73700d4555d2",
771 | "showTitle": false,
772 | "title": ""
773 | }
774 | },
775 | "outputs": [
776 | {
777 | "data": {
778 | "text/plain": [
779 | "I'm a Vehicle!\n",
780 | "I'm a Car!\n",
781 | "I'm a Truck!\n"
782 | ]
783 | },
784 | "metadata": {
785 | "application/vnd.databricks.v1+output": {
786 | "addedWidgets": {},
787 | "arguments": {},
788 | "data": "I'm a Vehicle!\nI'm a Car!\nI'm a Truck!\n",
789 | "datasetInfos": [],
790 | "metadata": {},
791 | "removedWidgets": [],
792 | "type": "ansi"
793 | }
794 | },
795 | "output_type": "display_data"
796 | }
797 | ],
798 | "source": [
799 | "# base class\n",
800 | "class Vehicle():\n",
801 | " def description(self):\n",
802 | " print(\"I'm a Vehicle!\")\n",
803 | "\n",
804 | "# subclass\n",
805 | "class Car(Vehicle):\n",
806 | " def description(self):\n",
807 | " print(\"I'm a Car!\")\n",
808 | " \n",
809 | "# another subclass\n",
810 | "class Truck(Vehicle):\n",
811 | " def description(self):\n",
812 | " print(\"I'm a Truck!\")\n",
813 | "\n",
814 | "# create an object from each class\n",
815 | "v = Vehicle()\n",
816 | "c = Car()\n",
817 | "t= Truck()\n",
818 | "\n",
819 | "v.description()\n",
820 | "# Prints I'm a Vehicle!\n",
821 | "\n",
822 | "c.description()\n",
823 | "# Prints I'm a Car!\n",
824 | "\n",
825 | "t.description()\n",
826 | "# Prints I'm a Truck!"
827 | ]
828 | },
829 | {
830 | "cell_type": "markdown",
831 | "metadata": {
832 | "application/vnd.databricks.v1+cell": {
833 | "inputWidgets": {},
834 | "nuid": "a5145610-3bb8-4f73-bab1-0e16af983b47",
835 | "showTitle": false,
836 | "title": ""
837 | }
838 | },
839 | "source": [
840 | "**Add a Method**\n",
841 | "\n",
842 | "The subclass can also add a method that was not present in its base class.\n",
843 | "\n",
844 | "Let’s define the new method setSpeed() for Car class."
845 | ]
846 | },
847 | {
848 | "cell_type": "code",
849 | "execution_count": 0,
850 | "metadata": {
851 | "application/vnd.databricks.v1+cell": {
852 | "inputWidgets": {},
853 | "nuid": "59355036-37b2-4184-91e7-4224ad50bd97",
854 | "showTitle": false,
855 | "title": ""
856 | }
857 | },
858 | "outputs": [
859 | {
860 | "data": {
861 | "text/plain": [
862 | "Now traveling at 25 miles per hour\n"
863 | ]
864 | },
865 | "metadata": {
866 | "application/vnd.databricks.v1+output": {
867 | "addedWidgets": {},
868 | "arguments": {},
869 | "data": "Now traveling at 25 miles per hour\n",
870 | "datasetInfos": [],
871 | "metadata": {},
872 | "removedWidgets": [],
873 | "type": "ansi"
874 | }
875 | },
876 | "output_type": "display_data"
877 | }
878 | ],
879 | "source": [
880 | "# a parent class\n",
881 | "class Vehicle():\n",
882 | " def description(self):\n",
883 | " print(\"I'm a\", self.color, \"Vehicle\")\n",
884 | "\n",
885 | "# subclass\n",
886 | "class Car(Vehicle):\n",
887 | " def description(self):\n",
888 | " print(\"I'm a\", self.color, self.style)\n",
889 | " def setSpeed(self, speed):\n",
890 | " print(\"Now traveling at\", speed,\"miles per hour\") \n",
891 | "\n",
892 | "# create an object from each class\n",
893 | "v = Vehicle()\n",
894 | "c = Car()\n",
895 | "\n",
896 | "c.setSpeed(25)\n",
897 | "# Prints Now traveling at 25 miles per hour"
898 | ]
899 | },
900 | {
901 | "cell_type": "code",
902 | "execution_count": 0,
903 | "metadata": {
904 | "application/vnd.databricks.v1+cell": {
905 | "inputWidgets": {},
906 | "nuid": "2b976422-a170-4b97-900f-ba60957ba50e",
907 | "showTitle": false,
908 | "title": ""
909 | }
910 | },
911 | "outputs": [
912 | {
913 | "data": {
914 | "text/plain": [
915 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n",
916 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)\n",
917 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n",
918 | "\u001b[0;32m----> 1\u001b[0;31m \u001b[0mv\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msetSpeed\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m25\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
919 | "\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0;31m# Triggers AttributeError: 'Vehicle' object has no attribute 'setSpeed'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
920 | "\n",
921 | "\u001b[0;31mAttributeError\u001b[0m: 'Vehicle' object has no attribute 'setSpeed'"
922 | ]
923 | },
924 | "metadata": {
925 | "application/vnd.databricks.v1+output": {
926 | "arguments": {},
927 | "data": "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)\n\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mv\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msetSpeed\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m25\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0;31m# Triggers AttributeError: 'Vehicle' object has no attribute 'setSpeed'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\n\u001b[0;31mAttributeError\u001b[0m: 'Vehicle' object has no attribute 'setSpeed'",
928 | "errorSummary": "AttributeError: 'Vehicle' object has no attribute 'setSpeed'",
929 | "errorTraceType": "ansi",
930 | "metadata": {},
931 | "type": "ipynbError"
932 | }
933 | },
934 | "output_type": "display_data"
935 | }
936 | ],
937 | "source": [
938 | "v.setSpeed(25)\n",
939 | "# Triggers AttributeError: 'Vehicle' object has no attribute 'setSpeed'"
940 | ]
941 | },
942 | {
943 | "cell_type": "markdown",
944 | "metadata": {
945 | "application/vnd.databricks.v1+cell": {
946 | "inputWidgets": {},
947 | "nuid": "797049ef-63b3-43a5-a823-0671755cacc5",
948 | "showTitle": false,
949 | "title": ""
950 | }
951 | },
952 | "source": [
953 | "**The super() Function**\n",
954 | "\n",
955 | "When you override a method, you sometimes want to reuse the method of the base class and add some new stuff.\n",
956 | "\n",
957 | "You can achieve this by using the super() Function. To demonstrate this, let’s redefine our Vehicle and Car class, but this time with the `__init__()` method.\n",
958 | "\n",
959 | "Notice that the `__init__()` call in the Vehicle class has only ‘color’ parameter while the Car class has an additional ‘style’ parameter."
960 | ]
961 | },
962 | {
963 | "cell_type": "code",
964 | "execution_count": 0,
965 | "metadata": {
966 | "application/vnd.databricks.v1+cell": {
967 | "inputWidgets": {},
968 | "nuid": "df1222e8-36ab-415c-8c3c-3c48bf9481c7",
969 | "showTitle": false,
970 | "title": ""
971 | }
972 | },
973 | "outputs": [
974 | {
975 | "data": {
976 | "text/plain": [
977 | "I'm a Red Vehicle\n",
978 | "I'm a Black Vehicle\n"
979 | ]
980 | },
981 | "metadata": {
982 | "application/vnd.databricks.v1+output": {
983 | "addedWidgets": {},
984 | "arguments": {},
985 | "data": "I'm a Red Vehicle\nI'm a Black Vehicle\n",
986 | "datasetInfos": [],
987 | "metadata": {},
988 | "removedWidgets": [],
989 | "type": "ansi"
990 | }
991 | },
992 | "output_type": "display_data"
993 | }
994 | ],
995 | "source": [
996 | "# base class\n",
997 | "class Vehicle():\n",
998 | " def __init__(self, color):\n",
999 | " self.color = color\n",
1000 | " def description(self):\n",
1001 | " print(\"I'm a\", self.color, \"Vehicle\")\n",
1002 | "\n",
1003 | "# subclass\n",
1004 | "class Car(Vehicle):\n",
1005 | " def __init__(self, color, style):\n",
1006 | " super().__init__(color) # invoke Vehicle’s __init__() method\n",
1007 | " self.style = style\n",
1008 | "\n",
1009 | "# create an object from each class\n",
1010 | "v = Vehicle('Red')\n",
1011 | "c = Car('Black', 'SUV')\n",
1012 | "\n",
1013 | "v.description()\n",
1014 | "# Prints I'm a Red Vehicle\n",
1015 | "c.description()"
1016 | ]
1017 | },
1018 | {
1019 | "cell_type": "code",
1020 | "execution_count": 0,
1021 | "metadata": {
1022 | "application/vnd.databricks.v1+cell": {
1023 | "inputWidgets": {},
1024 | "nuid": "41ef45ec-018c-4edf-a184-238285781357",
1025 | "showTitle": false,
1026 | "title": ""
1027 | }
1028 | },
1029 | "outputs": [
1030 | {
1031 | "data": {
1032 | "text/plain": [
1033 | "I'm a Red Vehicle\n",
1034 | "I'm a Black Vehicle\n"
1035 | ]
1036 | },
1037 | "metadata": {
1038 | "application/vnd.databricks.v1+output": {
1039 | "addedWidgets": {},
1040 | "arguments": {},
1041 | "data": "I'm a Red Vehicle\nI'm a Black Vehicle\n",
1042 | "datasetInfos": [],
1043 | "metadata": {},
1044 | "removedWidgets": [],
1045 | "type": "ansi"
1046 | }
1047 | },
1048 | "output_type": "display_data"
1049 | }
1050 | ],
1051 | "source": [
1052 | "# base class\n",
1053 | "class Vehicle():\n",
1054 | " def __init__(self, color):\n",
1055 | " self.color = color\n",
1056 | " def description(self):\n",
1057 | " print(\"I'm a\", self.color, \"Vehicle\")\n",
1058 | "\n",
1059 | "# subclass\n",
1060 | "class Car(Vehicle):\n",
1061 | " def __init__(self, color, style):\n",
1062 | " super().__init__(color) # invoke Vehicle’s __init__() method\n",
1063 | " self.style = style\n",
1064 | "\n",
1065 | "# create an object from each class\n",
1066 | "v = Vehicle('Red')\n",
1067 | "c = Car('Black', 'SUV')\n",
1068 | "\n",
1069 | "v.description()\n",
1070 | "# Prints I'm a Red Vehicle\n",
1071 | "c.description()\n",
1072 | "# Prints I'm a Red Vehicle"
1073 | ]
1074 | },
1075 | {
1076 | "cell_type": "code",
1077 | "execution_count": 0,
1078 | "metadata": {
1079 | "application/vnd.databricks.v1+cell": {
1080 | "inputWidgets": {},
1081 | "nuid": "7a3374a5-c42b-415b-864d-864d83971931",
1082 | "showTitle": false,
1083 | "title": ""
1084 | }
1085 | },
1086 | "outputs": [
1087 | {
1088 | "data": {
1089 | "text/plain": [
1090 | "I'm a Red Vehicle\n",
1091 | "I'm a Black SUV\n"
1092 | ]
1093 | },
1094 | "metadata": {
1095 | "application/vnd.databricks.v1+output": {
1096 | "addedWidgets": {},
1097 | "arguments": {},
1098 | "data": "I'm a Red Vehicle\nI'm a Black SUV\n",
1099 | "datasetInfos": [],
1100 | "metadata": {},
1101 | "removedWidgets": [],
1102 | "type": "ansi"
1103 | }
1104 | },
1105 | "output_type": "display_data"
1106 | }
1107 | ],
1108 | "source": [
1109 | "# base class\n",
1110 | "class Vehicle():\n",
1111 | " def __init__(self, color):\n",
1112 | " self.color = color\n",
1113 | " def description(self):\n",
1114 | " print(\"I'm a\", self.color, \"Vehicle\")\n",
1115 | "\n",
1116 | "# subclass\n",
1117 | "class Car(Vehicle):\n",
1118 | " def __init__(self, color, style):\n",
1119 | " super().__init__(color) # invoke Vehicle’s __init__() method\n",
1120 | " self.style = style\n",
1121 | " def description(self):\n",
1122 | " print(\"I'm a\", self.color, self.style)\n",
1123 | "\n",
1124 | "# create an object from each class\n",
1125 | "v = Vehicle('Red')\n",
1126 | "c = Car('Black', 'SUV')\n",
1127 | "\n",
1128 | "v.description()\n",
1129 | "# Prints I'm a Red Vehicle\n",
1130 | "c.description()\n",
1131 | "# Prints I'm a Black SUV"
1132 | ]
1133 | },
1134 | {
1135 | "cell_type": "markdown",
1136 | "metadata": {
1137 | "application/vnd.databricks.v1+cell": {
1138 | "inputWidgets": {},
1139 | "nuid": "33e64c80-7fa3-4311-bfcd-1561196b143d",
1140 | "showTitle": false,
1141 | "title": ""
1142 | }
1143 | },
1144 | "source": [
1145 | "**Multiple Inheritance**\n",
1146 | "\n",
1147 | "Python also supports multiple inheritance, where a subclass can inherit from multiple superclasses.\n",
1148 | "\n",
1149 | "In multiple inheritance, the characteristics of all the superclasses are inherited into the subclass.\n",
1150 | "\n",
1151 | "
"
1152 | ]
1153 | },
1154 | {
1155 | "cell_type": "code",
1156 | "execution_count": 0,
1157 | "metadata": {
1158 | "application/vnd.databricks.v1+cell": {
1159 | "inputWidgets": {},
1160 | "nuid": "3cd78b1b-7238-4db4-85a8-ea7788abf487",
1161 | "showTitle": false,
1162 | "title": ""
1163 | }
1164 | },
1165 | "outputs": [
1166 | {
1167 | "data": {
1168 | "text/plain": [
1169 | "Drive me on the road!\n",
1170 | "Fly me to the sky!\n"
1171 | ]
1172 | },
1173 | "metadata": {
1174 | "application/vnd.databricks.v1+output": {
1175 | "addedWidgets": {},
1176 | "arguments": {},
1177 | "data": "Drive me on the road!\nFly me to the sky!\n",
1178 | "datasetInfos": [],
1179 | "metadata": {},
1180 | "removedWidgets": [],
1181 | "type": "ansi"
1182 | }
1183 | },
1184 | "output_type": "display_data"
1185 | }
1186 | ],
1187 | "source": [
1188 | "# base class 1\n",
1189 | "class GroundVehicle():\n",
1190 | " def drive(self):\n",
1191 | " print(\"Drive me on the road!\")\n",
1192 | "\n",
1193 | "# base class 2\n",
1194 | "class FlyingVehicle():\n",
1195 | " def fly(self):\n",
1196 | " print(\"Fly me to the sky!\")\n",
1197 | "\n",
1198 | "# subclass\n",
1199 | "class FlyingCar(GroundVehicle, FlyingVehicle):\n",
1200 | " pass\n",
1201 | "\n",
1202 | "# create an object of a subclass\n",
1203 | "fc = FlyingCar()\n",
1204 | "\n",
1205 | "fc.drive()\n",
1206 | "# Prints Drive me on the road!\n",
1207 | "fc.fly()\n",
1208 | "# Prints Fly me to the sky!"
1209 | ]
1210 | }
1211 | ],
1212 | "metadata": {
1213 | "anaconda-cloud": {},
1214 | "application/vnd.databricks.v1+notebook": {
1215 | "dashboards": [],
1216 | "language": "python",
1217 | "notebookMetadata": {
1218 | "pythonIndentUnit": 2
1219 | },
1220 | "notebookName": "Python_Part4",
1221 | "notebookOrigID": 910232701719373,
1222 | "widgets": {}
1223 | },
1224 | "kernelspec": {
1225 | "display_name": "Python 3",
1226 | "language": "python",
1227 | "name": "python3"
1228 | },
1229 | "language_info": {
1230 | "codemirror_mode": {
1231 | "name": "ipython",
1232 | "version": 3
1233 | },
1234 | "file_extension": ".py",
1235 | "mimetype": "text/x-python",
1236 | "name": "python",
1237 | "nbconvert_exporter": "python",
1238 | "pygments_lexer": "ipython3",
1239 | "version": "3.7.3"
1240 | }
1241 | },
1242 | "nbformat": 4,
1243 | "nbformat_minor": 1
1244 | }
1245 |
--------------------------------------------------------------------------------
/Python/Python_Part5.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Python for Data Science and Machine Learning - Part 5\n",
8 | "--------"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "metadata": {
14 | "application/vnd.databricks.v1+cell": {
15 | "inputWidgets": {},
16 | "nuid": "ecfe6b18-e725-4a6f-b475-4d78be5faa74",
17 | "showTitle": false,
18 | "title": ""
19 | }
20 | },
21 | "source": [
22 | "## Functions\n",
23 | "\n",
24 | "A function is a relationship or mapping between one or more inputs and a set of outputs. Mathematically, a function is generally represented as follows:\n",
25 | "\n",
26 | "
\n",
27 | "\n",
28 | "where f is a function that operates on the inputs x and y and generates z as an output. In programming, a function is a self-contained block of code that encapsulates a specific task or related group of tasks. The functions allow us to define a reusable block of code that can be used repeatedly in a program.\n",
29 | "\n",
30 | "Python provides several built-in functions such as print(), len() and type(), but we can also define our own functions to use within our programs."
31 | ]
32 | },
33 | {
34 | "cell_type": "markdown",
35 | "metadata": {
36 | "application/vnd.databricks.v1+cell": {
37 | "inputWidgets": {},
38 | "nuid": "cd7ac8e4-73aa-44cf-acdb-1d21599d5c75",
39 | "showTitle": false,
40 | "title": ""
41 | }
42 | },
43 | "source": [
44 | "**Syntax**\n",
45 | "\n",
46 | "The basic syntax for a Python function definition is:\n",
47 | "\n",
48 | "
"
49 | ]
50 | },
51 | {
52 | "cell_type": "markdown",
53 | "metadata": {
54 | "application/vnd.databricks.v1+cell": {
55 | "inputWidgets": {},
56 | "nuid": "a029be1e-96d1-44b8-9358-1d91e01d33ff",
57 | "showTitle": false,
58 | "title": ""
59 | }
60 | },
61 | "source": [
62 | "**Create a function**\n",
63 | "\n",
64 | "A function is defined using the `def` keyword."
65 | ]
66 | },
67 | {
68 | "cell_type": "code",
69 | "execution_count": 1,
70 | "metadata": {
71 | "application/vnd.databricks.v1+cell": {
72 | "inputWidgets": {},
73 | "nuid": "8e9f77ee-46cd-4c1d-b216-75b1a5824ec5",
74 | "showTitle": false,
75 | "title": ""
76 | }
77 | },
78 | "outputs": [],
79 | "source": [
80 | "def hello():\n",
81 | " print(\"Hello World!\")"
82 | ]
83 | },
84 | {
85 | "cell_type": "markdown",
86 | "metadata": {
87 | "application/vnd.databricks.v1+cell": {
88 | "inputWidgets": {},
89 | "nuid": "da5c6e8f-1a8b-457f-89fb-880a9b895068",
90 | "showTitle": false,
91 | "title": ""
92 | }
93 | },
94 | "source": [
95 | "**Call a function**"
96 | ]
97 | },
98 | {
99 | "cell_type": "code",
100 | "execution_count": 2,
101 | "metadata": {
102 | "application/vnd.databricks.v1+cell": {
103 | "inputWidgets": {},
104 | "nuid": "677125a6-a39b-4cc8-97a4-15c57f09b2a7",
105 | "showTitle": false,
106 | "title": ""
107 | }
108 | },
109 | "outputs": [
110 | {
111 | "name": "stdout",
112 | "output_type": "stream",
113 | "text": [
114 | "Hello World!\n"
115 | ]
116 | }
117 | ],
118 | "source": [
119 | "hello()"
120 | ]
121 | },
122 | {
123 | "cell_type": "markdown",
124 | "metadata": {
125 | "application/vnd.databricks.v1+cell": {
126 | "inputWidgets": {},
127 | "nuid": "b7943bb3-7623-4d93-932e-c5ec1ac0dcfb",
128 | "showTitle": false,
129 | "title": ""
130 | }
131 | },
132 | "source": [
133 | "**Pass Arguments**\n",
134 | "\n",
135 | "We can pass values, known as arguments, to a function that are declared after the function name in parentheses."
136 | ]
137 | },
138 | {
139 | "cell_type": "code",
140 | "execution_count": 3,
141 | "metadata": {
142 | "application/vnd.databricks.v1+cell": {
143 | "inputWidgets": {},
144 | "nuid": "5372c866-82e0-4494-8f11-44c3d2883894",
145 | "showTitle": false,
146 | "title": ""
147 | }
148 | },
149 | "outputs": [],
150 | "source": [
151 | "# pass a single argument\n",
152 | "def hello(name):\n",
153 | " print('Hello,', name)\n",
154 | " \n",
155 | "# pass mutiple arguments\n",
156 | "\n",
157 | "def func(country,city):\n",
158 | " print(f'{city} is the capital of {country}')"
159 | ]
160 | },
161 | {
162 | "cell_type": "code",
163 | "execution_count": 4,
164 | "metadata": {
165 | "application/vnd.databricks.v1+cell": {
166 | "inputWidgets": {},
167 | "nuid": "0052e5f6-ebe7-438f-9cd4-8dd40c5b271b",
168 | "showTitle": false,
169 | "title": ""
170 | }
171 | },
172 | "outputs": [
173 | {
174 | "name": "stdout",
175 | "output_type": "stream",
176 | "text": [
177 | "Hello, Messi\n",
178 | "Paris is the capital of France\n"
179 | ]
180 | }
181 | ],
182 | "source": [
183 | "hello('Messi')\n",
184 | "func('France','Paris')"
185 | ]
186 | },
187 | {
188 | "cell_type": "markdown",
189 | "metadata": {
190 | "application/vnd.databricks.v1+cell": {
191 | "inputWidgets": {},
192 | "nuid": "73db98cf-97bc-4162-933c-9b1ab6cfd3b4",
193 | "showTitle": false,
194 | "title": ""
195 | }
196 | },
197 | "source": [
198 | "**Type of Arguments**\n",
199 | "\n",
200 | "1. Positional Arguments\n",
201 | "2. Keyword Arguments\n",
202 | "3. Default Arguments\n",
203 | "4. Variable Length Positional Arguments (*args)\n",
204 | "5. Variable Length Keyword Arguments (**kwargs)"
205 | ]
206 | },
207 | {
208 | "cell_type": "markdown",
209 | "metadata": {
210 | "application/vnd.databricks.v1+cell": {
211 | "inputWidgets": {},
212 | "nuid": "3f3e25cb-8284-4691-a223-2fe88ef592e5",
213 | "showTitle": false,
214 | "title": ""
215 | }
216 | },
217 | "source": [
218 | "Positional arguments - The positional argumentsare passed to the respective parameters in order."
219 | ]
220 | },
221 | {
222 | "cell_type": "code",
223 | "execution_count": 5,
224 | "metadata": {
225 | "application/vnd.databricks.v1+cell": {
226 | "inputWidgets": {},
227 | "nuid": "4f06a2ad-ad62-4b5e-944d-92b780f21fc9",
228 | "showTitle": false,
229 | "title": ""
230 | }
231 | },
232 | "outputs": [
233 | {
234 | "name": "stdout",
235 | "output_type": "stream",
236 | "text": [
237 | "Paris is the capital of France\n"
238 | ]
239 | }
240 | ],
241 | "source": [
242 | "# positional arguments\n",
243 | "def func(country,city):\n",
244 | " print(f'{city} is the capital of {country}')\n",
245 | " \n",
246 | "func('France','Paris')"
247 | ]
248 | },
249 | {
250 | "cell_type": "markdown",
251 | "metadata": {
252 | "application/vnd.databricks.v1+cell": {
253 | "inputWidgets": {},
254 | "nuid": "44dcb712-ba20-476c-b353-995da0004c2e",
255 | "showTitle": false,
256 | "title": ""
257 | }
258 | },
259 | "source": [
260 | "Keyword arguments - Pass arguments using the names of their corresponding parameters"
261 | ]
262 | },
263 | {
264 | "cell_type": "code",
265 | "execution_count": 6,
266 | "metadata": {
267 | "application/vnd.databricks.v1+cell": {
268 | "inputWidgets": {},
269 | "nuid": "53238ce6-1317-4f4d-b0c9-0ff15196a4d7",
270 | "showTitle": false,
271 | "title": ""
272 | }
273 | },
274 | "outputs": [
275 | {
276 | "name": "stdout",
277 | "output_type": "stream",
278 | "text": [
279 | "Paris is the capital of France\n"
280 | ]
281 | }
282 | ],
283 | "source": [
284 | "# keyword arguments can be put in any order\n",
285 | "def func(country,city):\n",
286 | " print(f'{city} is the capital of {country}')\n",
287 | "\n",
288 | "func(city='Paris',country='France')"
289 | ]
290 | },
291 | {
292 | "cell_type": "markdown",
293 | "metadata": {
294 | "application/vnd.databricks.v1+cell": {
295 | "inputWidgets": {},
296 | "nuid": "b0946438-9ce1-41ac-bee9-2cec5dbd8bd9",
297 | "showTitle": false,
298 | "title": ""
299 | }
300 | },
301 | "source": [
302 | "Default arguments - The default value is used when the no argument is passed durina a function call"
303 | ]
304 | },
305 | {
306 | "cell_type": "code",
307 | "execution_count": 7,
308 | "metadata": {
309 | "application/vnd.databricks.v1+cell": {
310 | "inputWidgets": {},
311 | "nuid": "6074fe1a-221b-482e-85d8-b9a56f5eabf0",
312 | "showTitle": false,
313 | "title": ""
314 | }
315 | },
316 | "outputs": [
317 | {
318 | "name": "stdout",
319 | "output_type": "stream",
320 | "text": [
321 | "Paris is the capital of France\n"
322 | ]
323 | }
324 | ],
325 | "source": [
326 | "def func(country,city = 'Paris'):\n",
327 | " print(f'{city} is the capital of {country}')\n",
328 | " \n",
329 | "func('France')"
330 | ]
331 | },
332 | {
333 | "cell_type": "markdown",
334 | "metadata": {
335 | "application/vnd.databricks.v1+cell": {
336 | "inputWidgets": {},
337 | "nuid": "e5d8309a-2b9d-4eb6-8553-89e6faf6b10f",
338 | "showTitle": false,
339 | "title": ""
340 | }
341 | },
342 | "source": [
343 | "Note: The default argument should be preceeded by non-default arguments"
344 | ]
345 | },
346 | {
347 | "cell_type": "markdown",
348 | "metadata": {
349 | "application/vnd.databricks.v1+cell": {
350 | "inputWidgets": {},
351 | "nuid": "ca65a173-3716-4fe5-a086-5aa7f610018f",
352 | "showTitle": false,
353 | "title": ""
354 | }
355 | },
356 | "source": [
357 | "Variable length arguments - Pass variable number of arguments to a function using special symbols\n",
358 | "\n",
359 | "- *args - arugments\n",
360 | "- **kwargs - keyword arguments"
361 | ]
362 | },
363 | {
364 | "cell_type": "code",
365 | "execution_count": 8,
366 | "metadata": {
367 | "application/vnd.databricks.v1+cell": {
368 | "inputWidgets": {},
369 | "nuid": "ea83fe74-3f93-4c68-86f9-d249c0ff9765",
370 | "showTitle": false,
371 | "title": ""
372 | }
373 | },
374 | "outputs": [
375 | {
376 | "name": "stdout",
377 | "output_type": "stream",
378 | "text": [
379 | "6\n"
380 | ]
381 | }
382 | ],
383 | "source": [
384 | "# sum integers using *args\n",
385 | "def my_sum(*args):\n",
386 | " result = 0\n",
387 | " # Iterating over the Python args tuple\n",
388 | " for x in args:\n",
389 | " result += x\n",
390 | " return result\n",
391 | "\n",
392 | "print(my_sum(1, 2, 3))"
393 | ]
394 | },
395 | {
396 | "cell_type": "code",
397 | "execution_count": 9,
398 | "metadata": {
399 | "application/vnd.databricks.v1+cell": {
400 | "inputWidgets": {},
401 | "nuid": "975d9247-ade6-4a38-a12e-0d9af8a33712",
402 | "showTitle": false,
403 | "title": ""
404 | }
405 | },
406 | "outputs": [
407 | {
408 | "name": "stdout",
409 | "output_type": "stream",
410 | "text": [
411 | "RealPythonIsGreat!\n"
412 | ]
413 | }
414 | ],
415 | "source": [
416 | "# concatenate strings using **kwargs\n",
417 | "def concatenate(**kwargs):\n",
418 | " result = \"\"\n",
419 | " # Iterating over the Python kwargs dictionary\n",
420 | " for arg in kwargs.values():\n",
421 | " result += arg\n",
422 | " return result\n",
423 | "\n",
424 | "print(concatenate(a=\"Real\", b=\"Python\", c=\"Is\", d=\"Great\", e=\"!\"))"
425 | ]
426 | },
427 | {
428 | "cell_type": "markdown",
429 | "metadata": {
430 | "application/vnd.databricks.v1+cell": {
431 | "inputWidgets": {},
432 | "nuid": "1eb92d78-6c22-4231-b232-f624ca0e1784",
433 | "showTitle": false,
434 | "title": ""
435 | }
436 | },
437 | "source": [
438 | "**Return value(s)**"
439 | ]
440 | },
441 | {
442 | "cell_type": "code",
443 | "execution_count": 10,
444 | "metadata": {
445 | "application/vnd.databricks.v1+cell": {
446 | "inputWidgets": {},
447 | "nuid": "c81aaf39-1662-43a0-aa37-cb411cdd934a",
448 | "showTitle": false,
449 | "title": ""
450 | }
451 | },
452 | "outputs": [
453 | {
454 | "data": {
455 | "text/plain": [
456 | "5"
457 | ]
458 | },
459 | "execution_count": 10,
460 | "metadata": {},
461 | "output_type": "execute_result"
462 | }
463 | ],
464 | "source": [
465 | "# return a single value\n",
466 | "def my_sum(a,b):\n",
467 | " return a+b\n",
468 | "my_sum(2,3)"
469 | ]
470 | },
471 | {
472 | "cell_type": "code",
473 | "execution_count": 11,
474 | "metadata": {
475 | "application/vnd.databricks.v1+cell": {
476 | "inputWidgets": {},
477 | "nuid": "c06e18dc-17e7-40f7-a5e9-96598d0ca75e",
478 | "showTitle": false,
479 | "title": ""
480 | }
481 | },
482 | "outputs": [
483 | {
484 | "data": {
485 | "text/plain": [
486 | "(5, 1)"
487 | ]
488 | },
489 | "execution_count": 11,
490 | "metadata": {},
491 | "output_type": "execute_result"
492 | }
493 | ],
494 | "source": [
495 | "# return multiple values\n",
496 | "\n",
497 | "def sum_diff(a,b):\n",
498 | " return a+b, a-b\n",
499 | "\n",
500 | "sum_diff(3,2)"
501 | ]
502 | },
503 | {
504 | "cell_type": "markdown",
505 | "metadata": {
506 | "application/vnd.databricks.v1+cell": {
507 | "inputWidgets": {},
508 | "nuid": "9d80eae8-4d80-424b-bb0f-c777c94fe560",
509 | "showTitle": false,
510 | "title": ""
511 | }
512 | },
513 | "source": [
514 | "**Docstring**\n",
515 | "\n",
516 | "Attach a documentation to a function definition by including a string right after the function header."
517 | ]
518 | },
519 | {
520 | "cell_type": "code",
521 | "execution_count": 12,
522 | "metadata": {
523 | "application/vnd.databricks.v1+cell": {
524 | "inputWidgets": {},
525 | "nuid": "7ffb5b20-96a3-4ab8-873a-1da7a9dd3533",
526 | "showTitle": false,
527 | "title": ""
528 | }
529 | },
530 | "outputs": [
531 | {
532 | "name": "stdout",
533 | "output_type": "stream",
534 | "text": [
535 | "Help on function hello in module __main__:\n",
536 | "\n",
537 | "hello()\n",
538 | " This function prints\n",
539 | " message on the screen\n",
540 | "\n",
541 | "This function prints\n",
542 | " message on the screen\n"
543 | ]
544 | }
545 | ],
546 | "source": [
547 | "def hello():\n",
548 | " \"\"\"This function prints\n",
549 | " message on the screen\"\"\" \n",
550 | " print('Hello, World!')\n",
551 | " \n",
552 | "help(hello)\n",
553 | "\n",
554 | "# print docstring\n",
555 | "print(hello.__doc__)"
556 | ]
557 | },
558 | {
559 | "cell_type": "markdown",
560 | "metadata": {
561 | "application/vnd.databricks.v1+cell": {
562 | "inputWidgets": {},
563 | "nuid": "2e7e7b4f-968e-4350-be87-12af7697b482",
564 | "showTitle": false,
565 | "title": ""
566 | }
567 | },
568 | "source": [
569 | "## Python Variables Scope\n",
570 | "\n",
571 | "The part of the program where the variable is accessible is called its “scope” and is determined by where the variable is declared. There are four variable scopes in python: local, enclosing, global and built-in scope."
572 | ]
573 | },
574 | {
575 | "cell_type": "markdown",
576 | "metadata": {
577 | "application/vnd.databricks.v1+cell": {
578 | "inputWidgets": {},
579 | "nuid": "a22fe445-bec3-4fcd-828b-1bed961ebbd5",
580 | "showTitle": false,
581 | "title": ""
582 | }
583 | },
584 | "source": [
585 | "**Local Scope**\n",
586 | "\n",
587 | "A variable that is declared within a function has a local scope and is accessible from the point where it is declared and until the end of the function."
588 | ]
589 | },
590 | {
591 | "cell_type": "code",
592 | "execution_count": 13,
593 | "metadata": {
594 | "application/vnd.databricks.v1+cell": {
595 | "inputWidgets": {},
596 | "nuid": "a609a817-c90a-4cb4-bba1-9725ee4afea3",
597 | "showTitle": false,
598 | "title": ""
599 | }
600 | },
601 | "outputs": [
602 | {
603 | "name": "stdout",
604 | "output_type": "stream",
605 | "text": [
606 | "Hello\n"
607 | ]
608 | }
609 | ],
610 | "source": [
611 | "def myfunc():\n",
612 | " x='Hello'\n",
613 | " print (x)\n",
614 | " \n",
615 | "myfunc()\n",
616 | "# print(x)\n",
617 | "# NameError: name 'x' is not defined"
618 | ]
619 | },
620 | {
621 | "cell_type": "markdown",
622 | "metadata": {
623 | "application/vnd.databricks.v1+cell": {
624 | "inputWidgets": {},
625 | "nuid": "7cddf61b-a646-4142-9e89-578abc4bc4e8",
626 | "showTitle": false,
627 | "title": ""
628 | }
629 | },
630 | "source": [
631 | "**Global Scope**"
632 | ]
633 | },
634 | {
635 | "cell_type": "code",
636 | "execution_count": 14,
637 | "metadata": {
638 | "application/vnd.databricks.v1+cell": {
639 | "inputWidgets": {},
640 | "nuid": "5ac67ade-0e14-451a-960b-3279e998e17b",
641 | "showTitle": false,
642 | "title": ""
643 | }
644 | },
645 | "outputs": [
646 | {
647 | "name": "stdout",
648 | "output_type": "stream",
649 | "text": [
650 | "Hello\n",
651 | "Hello\n"
652 | ]
653 | }
654 | ],
655 | "source": [
656 | "x = 'Hello'\n",
657 | "def myfunc():\n",
658 | " print(x)\n",
659 | "myfunc()\n",
660 | "print(x)"
661 | ]
662 | },
663 | {
664 | "cell_type": "markdown",
665 | "metadata": {
666 | "application/vnd.databricks.v1+cell": {
667 | "inputWidgets": {},
668 | "nuid": "ff3e3bd6-93aa-43be-b6c7-4524bb8eeebe",
669 | "showTitle": false,
670 | "title": ""
671 | }
672 | },
673 | "source": [
674 | "**Enclosing Scope**"
675 | ]
676 | },
677 | {
678 | "cell_type": "markdown",
679 | "metadata": {
680 | "application/vnd.databricks.v1+cell": {
681 | "inputWidgets": {},
682 | "nuid": "d7292ed5-b84c-47d2-a087-843912c1fa71",
683 | "showTitle": false,
684 | "title": ""
685 | }
686 | },
687 | "source": [
688 | "From inside, the `inner_func()`, the scope lies between a local and global scope and known as enclosing scope. Here, the value of existing variable x didn’t change because python created a new local variable named x that shadows the variable in the outer scope."
689 | ]
690 | },
691 | {
692 | "cell_type": "code",
693 | "execution_count": 15,
694 | "metadata": {
695 | "application/vnd.databricks.v1+cell": {
696 | "inputWidgets": {},
697 | "nuid": "bdeae6c6-aacf-4cfd-aae7-ea8abd25460d",
698 | "showTitle": false,
699 | "title": ""
700 | }
701 | },
702 | "outputs": [
703 | {
704 | "name": "stdout",
705 | "output_type": "stream",
706 | "text": [
707 | "0\n",
708 | "10\n"
709 | ]
710 | }
711 | ],
712 | "source": [
713 | "def outer_func():\n",
714 | " var = 10\n",
715 | " # nested function\n",
716 | " def inner_func():\n",
717 | " var = 0\n",
718 | " print(var) # x is 0\n",
719 | " inner_func()\n",
720 | " print(var) # x is still 10\n",
721 | "\n",
722 | "outer_func()"
723 | ]
724 | },
725 | {
726 | "cell_type": "markdown",
727 | "metadata": {
728 | "application/vnd.databricks.v1+cell": {
729 | "inputWidgets": {},
730 | "nuid": "223661d1-53eb-4c5d-8316-ff23d8e54a9a",
731 | "showTitle": false,
732 | "title": ""
733 | }
734 | },
735 | "source": [
736 | "By using `nonlocal` keyword, the x inside the nested function now refers to the x outside the function, so changing x inside the function changes the x outside it."
737 | ]
738 | },
739 | {
740 | "cell_type": "code",
741 | "execution_count": 16,
742 | "metadata": {
743 | "application/vnd.databricks.v1+cell": {
744 | "inputWidgets": {},
745 | "nuid": "6857b857-13b0-444c-a26f-7da82c768561",
746 | "showTitle": false,
747 | "title": ""
748 | }
749 | },
750 | "outputs": [
751 | {
752 | "name": "stdout",
753 | "output_type": "stream",
754 | "text": [
755 | "0\n",
756 | "0\n"
757 | ]
758 | }
759 | ],
760 | "source": [
761 | "# enclosing function\n",
762 | "def f1():\n",
763 | " x = 42\n",
764 | " # nested function\n",
765 | " def f2():\n",
766 | " nonlocal x\n",
767 | " x = 0\n",
768 | " print(x) # x is now 0\n",
769 | " f2()\n",
770 | " print(x) # x remains 0\n",
771 | " \n",
772 | "f1()"
773 | ]
774 | },
775 | {
776 | "cell_type": "markdown",
777 | "metadata": {
778 | "application/vnd.databricks.v1+cell": {
779 | "inputWidgets": {},
780 | "nuid": "58fdbb0d-8444-487a-aefe-04ebde20002f",
781 | "showTitle": false,
782 | "title": ""
783 | }
784 | },
785 | "source": [
786 | "**Scoping LEGB Rule**\n",
787 | "\n",
788 | "
\n",
789 | "\n",
790 | "When a variable is referenced, Python follows LEGB rule and searches up to four scopes in this order:\n",
791 | "\n",
792 | "1. first in the local (L) scope,\n",
793 | "\n",
794 | "2. then in the local scopes of any enclosing (E) functions and lambdas,\n",
795 | "\n",
796 | "3. then in the global (G) scope,\n",
797 | "\n",
798 | "4. and finally in then the built-in (B) scope"
799 | ]
800 | },
801 | {
802 | "cell_type": "markdown",
803 | "metadata": {
804 | "application/vnd.databricks.v1+cell": {
805 | "inputWidgets": {},
806 | "nuid": "ba685c45-b733-4b20-8dfb-290c941df96b",
807 | "showTitle": false,
808 | "title": ""
809 | }
810 | },
811 | "source": [
812 | "## Lambda Function\n",
813 | "\n",
814 | "A lambda function is an anonymous function created using the keyword `lambda`"
815 | ]
816 | },
817 | {
818 | "cell_type": "code",
819 | "execution_count": 17,
820 | "metadata": {
821 | "application/vnd.databricks.v1+cell": {
822 | "inputWidgets": {},
823 | "nuid": "1d150e8f-1ca8-46d4-8842-894f5414350d",
824 | "showTitle": false,
825 | "title": ""
826 | }
827 | },
828 | "outputs": [
829 | {
830 | "data": {
831 | "text/plain": [
832 | "4"
833 | ]
834 | },
835 | "execution_count": 17,
836 | "metadata": {},
837 | "output_type": "execute_result"
838 | }
839 | ],
840 | "source": [
841 | "double = lambda x:x**2\n",
842 | "double(2)"
843 | ]
844 | },
845 | {
846 | "cell_type": "code",
847 | "execution_count": 18,
848 | "metadata": {
849 | "application/vnd.databricks.v1+cell": {
850 | "inputWidgets": {},
851 | "nuid": "a402efdb-df29-4291-bd29-8eab53ef4abe",
852 | "showTitle": false,
853 | "title": ""
854 | }
855 | },
856 | "outputs": [
857 | {
858 | "data": {
859 | "text/plain": [
860 | "5"
861 | ]
862 | },
863 | "execution_count": 18,
864 | "metadata": {},
865 | "output_type": "execute_result"
866 | }
867 | ],
868 | "source": [
869 | "add = lambda x, y: x + y\n",
870 | "add(2,3)"
871 | ]
872 | },
873 | {
874 | "cell_type": "code",
875 | "execution_count": 19,
876 | "metadata": {
877 | "application/vnd.databricks.v1+cell": {
878 | "inputWidgets": {},
879 | "nuid": "f97bbb34-6a1d-475f-9030-ee79d0c5826c",
880 | "showTitle": false,
881 | "title": ""
882 | }
883 | },
884 | "outputs": [
885 | {
886 | "data": {
887 | "text/plain": [
888 | "1"
889 | ]
890 | },
891 | "execution_count": 19,
892 | "metadata": {},
893 | "output_type": "execute_result"
894 | }
895 | ],
896 | "source": [
897 | "my_list =[2,1,4]\n",
898 | "# returns the first element of the above list\n",
899 | "b = lambda x:x[1]\n",
900 | "b(my_list)"
901 | ]
902 | },
903 | {
904 | "cell_type": "markdown",
905 | "metadata": {
906 | "application/vnd.databricks.v1+cell": {
907 | "inputWidgets": {},
908 | "nuid": "3b5200f8-784d-4af4-a59b-f88d68dc13ca",
909 | "showTitle": false,
910 | "title": ""
911 | }
912 | },
913 | "source": [
914 | "**Lambdas with map, filter and reduce**"
915 | ]
916 | },
917 | {
918 | "cell_type": "markdown",
919 | "metadata": {
920 | "application/vnd.databricks.v1+cell": {
921 | "inputWidgets": {},
922 | "nuid": "d380304a-ad9f-4ce6-818a-ab012604e0a3",
923 | "showTitle": false,
924 | "title": ""
925 | }
926 | },
927 | "source": [
928 | "`map()` takes a function as a first argument and applies it to each of the elements of its second argument, an iterable (most commonly a list)."
929 | ]
930 | },
931 | {
932 | "cell_type": "code",
933 | "execution_count": 20,
934 | "metadata": {
935 | "application/vnd.databricks.v1+cell": {
936 | "inputWidgets": {},
937 | "nuid": "c98ddf3b-bdcf-4f2a-bcb2-e7aeb3a12369",
938 | "showTitle": false,
939 | "title": ""
940 | }
941 | },
942 | "outputs": [
943 | {
944 | "data": {
945 | "text/plain": [
946 | "[0, 2, 4]"
947 | ]
948 | },
949 | "execution_count": 20,
950 | "metadata": {},
951 | "output_type": "execute_result"
952 | }
953 | ],
954 | "source": [
955 | "list(map((lambda x: x*2), range(3)))"
956 | ]
957 | },
958 | {
959 | "cell_type": "code",
960 | "execution_count": 21,
961 | "metadata": {
962 | "application/vnd.databricks.v1+cell": {
963 | "inputWidgets": {},
964 | "nuid": "cfa3cc70-0b75-46b9-95c9-9cd7153f8755",
965 | "showTitle": false,
966 | "title": ""
967 | }
968 | },
969 | "outputs": [
970 | {
971 | "data": {
972 | "text/plain": [
973 | "['A', 'B', 'C']"
974 | ]
975 | },
976 | "execution_count": 21,
977 | "metadata": {},
978 | "output_type": "execute_result"
979 | }
980 | ],
981 | "source": [
982 | "list(map((lambda x: x.upper()), 'abc'))"
983 | ]
984 | },
985 | {
986 | "cell_type": "code",
987 | "execution_count": 22,
988 | "metadata": {
989 | "application/vnd.databricks.v1+cell": {
990 | "inputWidgets": {},
991 | "nuid": "eee521b8-5648-489c-91bf-27fdda9b9325",
992 | "showTitle": false,
993 | "title": ""
994 | }
995 | },
996 | "outputs": [
997 | {
998 | "data": {
999 | "text/plain": [
1000 | "['Cat', 'Dog', 'Cow']"
1001 | ]
1002 | },
1003 | "execution_count": 22,
1004 | "metadata": {},
1005 | "output_type": "execute_result"
1006 | }
1007 | ],
1008 | "source": [
1009 | "list(map(lambda x:x.capitalize(), ['cat', 'dog', 'cow']))"
1010 | ]
1011 | },
1012 | {
1013 | "cell_type": "markdown",
1014 | "metadata": {
1015 | "application/vnd.databricks.v1+cell": {
1016 | "inputWidgets": {},
1017 | "nuid": "aaecb617-7cac-4829-85a6-41eb34cedf68",
1018 | "showTitle": false,
1019 | "title": ""
1020 | }
1021 | },
1022 | "source": [
1023 | "`filter()` function is similar to the map(). It takes a function and applies it to each item in the list to create a new list with only those items that cause the function to return True."
1024 | ]
1025 | },
1026 | {
1027 | "cell_type": "code",
1028 | "execution_count": 23,
1029 | "metadata": {
1030 | "application/vnd.databricks.v1+cell": {
1031 | "inputWidgets": {},
1032 | "nuid": "825a75c9-51db-47c0-b8bf-55b166b64a19",
1033 | "showTitle": false,
1034 | "title": ""
1035 | }
1036 | },
1037 | "outputs": [
1038 | {
1039 | "data": {
1040 | "text/plain": [
1041 | "['dog', 'cow']"
1042 | ]
1043 | },
1044 | "execution_count": 23,
1045 | "metadata": {},
1046 | "output_type": "execute_result"
1047 | }
1048 | ],
1049 | "source": [
1050 | "list(filter(lambda x: 'o' in x, ['cat', 'dog', 'cow']))"
1051 | ]
1052 | },
1053 | {
1054 | "cell_type": "markdown",
1055 | "metadata": {
1056 | "application/vnd.databricks.v1+cell": {
1057 | "inputWidgets": {},
1058 | "nuid": "293147a2-9bbd-4878-ae20-bab9591420cb",
1059 | "showTitle": false,
1060 | "title": ""
1061 | }
1062 | },
1063 | "source": [
1064 | "`reduce()` applies a rolling calculation to all items in a list."
1065 | ]
1066 | },
1067 | {
1068 | "cell_type": "code",
1069 | "execution_count": 24,
1070 | "metadata": {
1071 | "application/vnd.databricks.v1+cell": {
1072 | "inputWidgets": {},
1073 | "nuid": "1481643a-fcee-4abd-9596-d73a34b2b5ca",
1074 | "showTitle": false,
1075 | "title": ""
1076 | }
1077 | },
1078 | "outputs": [
1079 | {
1080 | "data": {
1081 | "text/plain": [
1082 | "'cat | dog | cow'"
1083 | ]
1084 | },
1085 | "execution_count": 24,
1086 | "metadata": {},
1087 | "output_type": "execute_result"
1088 | }
1089 | ],
1090 | "source": [
1091 | "from functools import reduce\n",
1092 | "reduce(lambda acc, x: f'{acc} | {x}', ['cat', 'dog', 'cow'])"
1093 | ]
1094 | },
1095 | {
1096 | "cell_type": "markdown",
1097 | "metadata": {
1098 | "application/vnd.databricks.v1+cell": {
1099 | "inputWidgets": {},
1100 | "nuid": "6cbdc0fd-ed98-4143-b110-f9b6dccae802",
1101 | "showTitle": false,
1102 | "title": ""
1103 | }
1104 | },
1105 | "source": [
1106 | "**if else in a lambda**"
1107 | ]
1108 | },
1109 | {
1110 | "cell_type": "code",
1111 | "execution_count": 25,
1112 | "metadata": {
1113 | "application/vnd.databricks.v1+cell": {
1114 | "inputWidgets": {},
1115 | "nuid": "7e09eac6-14c7-4f3f-8cc8-131c13b87e8d",
1116 | "showTitle": false,
1117 | "title": ""
1118 | }
1119 | },
1120 | "outputs": [
1121 | {
1122 | "name": "stdout",
1123 | "output_type": "stream",
1124 | "text": [
1125 | "2\n"
1126 | ]
1127 | }
1128 | ],
1129 | "source": [
1130 | "exp = lambda x, y: x if x < y else y\n",
1131 | "\n",
1132 | "print(exp(2, 4))"
1133 | ]
1134 | },
1135 | {
1136 | "cell_type": "markdown",
1137 | "metadata": {
1138 | "application/vnd.databricks.v1+cell": {
1139 | "inputWidgets": {},
1140 | "nuid": "7fe858a3-e5dc-48ff-a4b6-123c8249ec35",
1141 | "showTitle": false,
1142 | "title": ""
1143 | }
1144 | },
1145 | "source": [
1146 | "**List comprehension in a lambda**"
1147 | ]
1148 | },
1149 | {
1150 | "cell_type": "code",
1151 | "execution_count": 26,
1152 | "metadata": {
1153 | "application/vnd.databricks.v1+cell": {
1154 | "inputWidgets": {},
1155 | "nuid": "06c9cfbb-dd5b-458c-81da-2e380ba7e4c8",
1156 | "showTitle": false,
1157 | "title": ""
1158 | }
1159 | },
1160 | "outputs": [
1161 | {
1162 | "name": "stdout",
1163 | "output_type": "stream",
1164 | "text": [
1165 | "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
1166 | ]
1167 | }
1168 | ],
1169 | "source": [
1170 | "flatten = lambda l: [item for sublist in l for item in sublist]\n",
1171 | "L = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]\n",
1172 | "print(flatten(L))"
1173 | ]
1174 | }
1175 | ],
1176 | "metadata": {
1177 | "anaconda-cloud": {},
1178 | "application/vnd.databricks.v1+notebook": {
1179 | "dashboards": [],
1180 | "language": "python",
1181 | "notebookMetadata": {
1182 | "pythonIndentUnit": 2
1183 | },
1184 | "notebookName": "Python_Functions",
1185 | "notebookOrigID": 3368454474745191,
1186 | "widgets": {}
1187 | },
1188 | "kernelspec": {
1189 | "display_name": "Python 3",
1190 | "language": "python",
1191 | "name": "python3"
1192 | },
1193 | "language_info": {
1194 | "codemirror_mode": {
1195 | "name": "ipython",
1196 | "version": 3
1197 | },
1198 | "file_extension": ".py",
1199 | "mimetype": "text/x-python",
1200 | "name": "python",
1201 | "nbconvert_exporter": "python",
1202 | "pygments_lexer": "ipython3",
1203 | "version": "3.7.3"
1204 | }
1205 | },
1206 | "nbformat": 4,
1207 | "nbformat_minor": 1
1208 | }
1209 |
--------------------------------------------------------------------------------
/Python/Python_Part6.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Python for Data Science and Machine Learning - Part 6\n",
8 | "--------"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "metadata": {
14 | "application/vnd.databricks.v1+cell": {
15 | "inputWidgets": {},
16 | "nuid": "be705f27-76b4-4600-a38c-17eb65028c91",
17 | "showTitle": false,
18 | "title": ""
19 | }
20 | },
21 | "source": [
22 | "## Decorators\n",
23 | "\n",
24 | "A decorator is a design pattern in Python that allows user to add new functionality to an existing object. Decorators are usually called before the definition of a function you want to decorate. \n",
25 | "\n",
26 | "Before we try to understand decorators by creating one, let's try to go over a fundamental concept that functions in python are first-class objects. This means that they can be passed as an argument, returend from function, modified and assigned to a variable, just like any other object(string, float, int, etc.)."
27 | ]
28 | },
29 | {
30 | "cell_type": "markdown",
31 | "metadata": {
32 | "application/vnd.databricks.v1+cell": {
33 | "inputWidgets": {},
34 | "nuid": "cbbad752-beb0-4ee0-b282-e1ea8ce1cd4e",
35 | "showTitle": false,
36 | "title": ""
37 | }
38 | },
39 | "source": [
40 | "**Assigning functions to variables**\n",
41 | "\n",
42 | "Here, we create a function that will add one to a number whenever it is called. We'll then assign the function to a variable and use this variable to call the function."
43 | ]
44 | },
45 | {
46 | "cell_type": "code",
47 | "execution_count": 1,
48 | "metadata": {
49 | "application/vnd.databricks.v1+cell": {
50 | "inputWidgets": {},
51 | "nuid": "e3bed68f-f56a-4a4b-8ae8-d36074daf439",
52 | "showTitle": false,
53 | "title": ""
54 | }
55 | },
56 | "outputs": [
57 | {
58 | "data": {
59 | "text/plain": [
60 | "6"
61 | ]
62 | },
63 | "execution_count": 1,
64 | "metadata": {},
65 | "output_type": "execute_result"
66 | }
67 | ],
68 | "source": [
69 | "def plus_one(number):\n",
70 | " return number + 1\n",
71 | "\n",
72 | "add_one = plus_one\n",
73 | "add_one(5)"
74 | ]
75 | },
76 | {
77 | "cell_type": "markdown",
78 | "metadata": {
79 | "application/vnd.databricks.v1+cell": {
80 | "inputWidgets": {},
81 | "nuid": "d213ab21-d72e-4bae-8baf-41aa567a8e0c",
82 | "showTitle": false,
83 | "title": ""
84 | }
85 | },
86 | "source": [
87 | "**Defining functions inside other functions**\n",
88 | "\n",
89 | "Here, we illustrate how to define a function inside another function."
90 | ]
91 | },
92 | {
93 | "cell_type": "code",
94 | "execution_count": 2,
95 | "metadata": {
96 | "application/vnd.databricks.v1+cell": {
97 | "inputWidgets": {},
98 | "nuid": "613abd42-3bd6-489b-90ad-b7c96cbf167d",
99 | "showTitle": false,
100 | "title": ""
101 | }
102 | },
103 | "outputs": [
104 | {
105 | "data": {
106 | "text/plain": [
107 | "5"
108 | ]
109 | },
110 | "execution_count": 2,
111 | "metadata": {},
112 | "output_type": "execute_result"
113 | }
114 | ],
115 | "source": [
116 | "def plus_one(number):\n",
117 | " def add_one(number):\n",
118 | " return number+1\n",
119 | " # assign function to a variable\n",
120 | " result = add_one(number)\n",
121 | " return result\n",
122 | "\n",
123 | "plus_one(4)"
124 | ]
125 | },
126 | {
127 | "cell_type": "markdown",
128 | "metadata": {
129 | "application/vnd.databricks.v1+cell": {
130 | "inputWidgets": {},
131 | "nuid": "cb65da7c-7e0c-4e9b-87ba-10fefe928ad0",
132 | "showTitle": false,
133 | "title": ""
134 | }
135 | },
136 | "source": [
137 | "**Passing functions as arguments to other functions**\n",
138 | "\n",
139 | "Functions can be passed as parameters to other functions."
140 | ]
141 | },
142 | {
143 | "cell_type": "code",
144 | "execution_count": 3,
145 | "metadata": {
146 | "application/vnd.databricks.v1+cell": {
147 | "inputWidgets": {},
148 | "nuid": "5b204555-c3b8-4132-a73d-fc7fc0623e89",
149 | "showTitle": false,
150 | "title": ""
151 | }
152 | },
153 | "outputs": [
154 | {
155 | "data": {
156 | "text/plain": [
157 | "6"
158 | ]
159 | },
160 | "execution_count": 3,
161 | "metadata": {},
162 | "output_type": "execute_result"
163 | }
164 | ],
165 | "source": [
166 | "def plus_one(number):\n",
167 | " return number+1\n",
168 | "\n",
169 | "def function_call(function):\n",
170 | " number_to_add = 5\n",
171 | " return function(number_to_add)\n",
172 | "\n",
173 | "function_call(plus_one)"
174 | ]
175 | },
176 | {
177 | "cell_type": "markdown",
178 | "metadata": {
179 | "application/vnd.databricks.v1+cell": {
180 | "inputWidgets": {},
181 | "nuid": "9ea26daf-ed8b-4ec4-a7aa-a0c32ae22b53",
182 | "showTitle": false,
183 | "title": ""
184 | }
185 | },
186 | "source": [
187 | "**Functions returning other functions**"
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": 4,
193 | "metadata": {
194 | "application/vnd.databricks.v1+cell": {
195 | "inputWidgets": {},
196 | "nuid": "85e7b62e-fcdb-4dcf-9664-13d2686cc7ee",
197 | "showTitle": false,
198 | "title": ""
199 | }
200 | },
201 | "outputs": [
202 | {
203 | "data": {
204 | "text/plain": [
205 | "'Hi'"
206 | ]
207 | },
208 | "execution_count": 4,
209 | "metadata": {},
210 | "output_type": "execute_result"
211 | }
212 | ],
213 | "source": [
214 | "def hello_function():\n",
215 | " def say_hi():\n",
216 | " return \"Hi\"\n",
217 | " return say_hi\n",
218 | "\n",
219 | "hello = hello_function()\n",
220 | "hello()"
221 | ]
222 | },
223 | {
224 | "cell_type": "code",
225 | "execution_count": 5,
226 | "metadata": {
227 | "application/vnd.databricks.v1+cell": {
228 | "inputWidgets": {},
229 | "nuid": "58e76d22-6cc1-4896-bd6b-a624c3b80ae4",
230 | "showTitle": false,
231 | "title": ""
232 | }
233 | },
234 | "outputs": [
235 | {
236 | "name": "stdout",
237 | "output_type": "stream",
238 | "text": [
239 | "Running inner\n"
240 | ]
241 | }
242 | ],
243 | "source": [
244 | "def outer_func():\n",
245 | " def inner_func():\n",
246 | " print ('Running inner')\n",
247 | " inner_func()\n",
248 | "\n",
249 | "outer_func()"
250 | ]
251 | },
252 | {
253 | "cell_type": "code",
254 | "execution_count": 6,
255 | "metadata": {
256 | "application/vnd.databricks.v1+cell": {
257 | "inputWidgets": {},
258 | "nuid": "fcb86ee8-47e4-44e8-8ace-c81bd554e574",
259 | "showTitle": false,
260 | "title": ""
261 | }
262 | },
263 | "outputs": [
264 | {
265 | "name": "stdout",
266 | "output_type": "stream",
267 | "text": [
268 | "hello\n"
269 | ]
270 | }
271 | ],
272 | "source": [
273 | "def to_lower(message):\n",
274 | " def message_sender():\n",
275 | " print(message.lower())\n",
276 | " message_sender()\n",
277 | "\n",
278 | "to_lower(\"HELLO\")"
279 | ]
280 | },
281 | {
282 | "cell_type": "markdown",
283 | "metadata": {
284 | "application/vnd.databricks.v1+cell": {
285 | "inputWidgets": {},
286 | "nuid": "e35f575c-1351-4573-8522-b3a57bc02774",
287 | "showTitle": false,
288 | "title": ""
289 | }
290 | },
291 | "source": [
292 | "### Creating decorators\n",
293 | "\n",
294 | "Here, we create a simple decorator that will convert a sentence to uppercase. First, we define a wrapper function inside an enclosed function. This step is similar to the concept of defining a function inside another function that was showcased earlier."
295 | ]
296 | },
297 | {
298 | "cell_type": "code",
299 | "execution_count": 7,
300 | "metadata": {
301 | "application/vnd.databricks.v1+cell": {
302 | "inputWidgets": {},
303 | "nuid": "c7106b69-e1c2-440f-8d64-615cb2272098",
304 | "showTitle": false,
305 | "title": ""
306 | }
307 | },
308 | "outputs": [],
309 | "source": [
310 | "def uppercase_decorator(function):\n",
311 | " def wrapper():\n",
312 | " func = function()\n",
313 | " make_uppercase = func.upper()\n",
314 | " return make_uppercase\n",
315 | " return wrapper"
316 | ]
317 | },
318 | {
319 | "cell_type": "markdown",
320 | "metadata": {
321 | "application/vnd.databricks.v1+cell": {
322 | "inputWidgets": {},
323 | "nuid": "2e77f06e-4cb3-4223-b04a-56d318dbda78",
324 | "showTitle": false,
325 | "title": ""
326 | }
327 | },
328 | "source": [
329 | "The decorator function takes a function as an argument. So next, we define a function and pass it to our decorator. We learned earlier that we could assign a function to a variable. We'll use that trick to call our decorator function."
330 | ]
331 | },
332 | {
333 | "cell_type": "code",
334 | "execution_count": 8,
335 | "metadata": {
336 | "application/vnd.databricks.v1+cell": {
337 | "inputWidgets": {},
338 | "nuid": "647e9426-c1ff-4994-b0e1-63751effb034",
339 | "showTitle": false,
340 | "title": ""
341 | },
342 | "scrolled": true
343 | },
344 | "outputs": [
345 | {
346 | "data": {
347 | "text/plain": [
348 | "'HELLO THERE'"
349 | ]
350 | },
351 | "execution_count": 8,
352 | "metadata": {},
353 | "output_type": "execute_result"
354 | }
355 | ],
356 | "source": [
357 | "def say_hi():\n",
358 | " return 'hello there'\n",
359 | "decorate = uppercase_decorator(say_hi)\n",
360 | "decorate()"
361 | ]
362 | },
363 | {
364 | "cell_type": "markdown",
365 | "metadata": {
366 | "application/vnd.databricks.v1+cell": {
367 | "inputWidgets": {},
368 | "nuid": "d97df887-d362-4627-9275-3dd80f263889",
369 | "showTitle": false,
370 | "title": ""
371 | }
372 | },
373 | "source": [
374 | "However, Python provides a much easier way for us to apply decorators. We simply use the @ symbol before the function we'd like to decorate. Let's show that in practice below."
375 | ]
376 | },
377 | {
378 | "cell_type": "code",
379 | "execution_count": 9,
380 | "metadata": {
381 | "application/vnd.databricks.v1+cell": {
382 | "inputWidgets": {},
383 | "nuid": "b75a0cc0-896f-4f32-a3ec-b750b0fa57af",
384 | "showTitle": false,
385 | "title": ""
386 | }
387 | },
388 | "outputs": [
389 | {
390 | "data": {
391 | "text/plain": [
392 | "'HELLO THERE'"
393 | ]
394 | },
395 | "execution_count": 9,
396 | "metadata": {},
397 | "output_type": "execute_result"
398 | }
399 | ],
400 | "source": [
401 | "@uppercase_decorator\n",
402 | "def say_hi():\n",
403 | " return 'hello there'\n",
404 | "say_hi()"
405 | ]
406 | },
407 | {
408 | "cell_type": "markdown",
409 | "metadata": {
410 | "application/vnd.databricks.v1+cell": {
411 | "inputWidgets": {},
412 | "nuid": "ca82b011-fb60-4a6d-a2b4-1d179f98aff3",
413 | "showTitle": false,
414 | "title": ""
415 | }
416 | },
417 | "source": [
418 | "**Execution explained**"
419 | ]
420 | },
421 | {
422 | "cell_type": "code",
423 | "execution_count": 10,
424 | "metadata": {
425 | "application/vnd.databricks.v1+cell": {
426 | "inputWidgets": {},
427 | "nuid": "456b204e-cd0c-4b60-97ed-d132e37c8371",
428 | "showTitle": false,
429 | "title": ""
430 | }
431 | },
432 | "outputs": [
433 | {
434 | "name": "stdout",
435 | "output_type": "stream",
436 | "text": [
437 | "Inside wrapper\n",
438 | "Hello world\n"
439 | ]
440 | }
441 | ],
442 | "source": [
443 | "def myWrapper(func):\n",
444 | " def myInnerfunc():\n",
445 | " print(\"Inside wrapper\")\n",
446 | " func()\n",
447 | " return myInnerfunc\n",
448 | "# decorate = myWrapper(myFunc)\n",
449 | "# decorate()\n",
450 | "@myWrapper\n",
451 | "def myFunc():\n",
452 | " print (\"Hello world\")\n",
453 | "myFunc()"
454 | ]
455 | },
456 | {
457 | "cell_type": "markdown",
458 | "metadata": {
459 | "application/vnd.databricks.v1+cell": {
460 | "inputWidgets": {},
461 | "nuid": "c833aa3c-bd9f-4436-9a21-f5c4572f37b2",
462 | "showTitle": false,
463 | "title": ""
464 | }
465 | },
466 | "source": [
467 | "
"
468 | ]
469 | },
470 | {
471 | "cell_type": "markdown",
472 | "metadata": {
473 | "application/vnd.databricks.v1+cell": {
474 | "inputWidgets": {},
475 | "nuid": "0c6eae4e-53ed-4574-9ffc-c49687f9fa23",
476 | "showTitle": false,
477 | "title": ""
478 | }
479 | },
480 | "source": [
481 | "Here, we are trying to decorate the `myFunc` function. using the decorator function `myWrapper`. Below are the steps of execution in the above code:\n",
482 | "\n",
483 | "**1. The original function `myFunc` is called.**\n",
484 | "
\n",
485 | "**2. There is a function wrapper name `@myWrapper` specified above the `myFunc` function definition. This indicates, there is a function decorator assigned to the function.**\n",
486 | "
\n",
487 | "**3. The decorator function `myWrapper` gets called. The program controller passes the function object as a parameter to the decorator function.**\n",
488 | "
\n",
489 | "**4. The function `myInnerFunc` inside the decorator function gets executed.**\n",
490 | "
\n",
491 | "**5. The inner function `myInnerFunc` calls the actual function `myFunc`.**\n",
492 | "
\n",
493 | "**6. The original function `myFunc` starts execution.**"
494 | ]
495 | },
496 | {
497 | "cell_type": "markdown",
498 | "metadata": {
499 | "application/vnd.databricks.v1+cell": {
500 | "inputWidgets": {},
501 | "nuid": "8fd21c68-cdaa-4652-a1a4-a89922c99a84",
502 | "showTitle": false,
503 | "title": ""
504 | }
505 | },
506 | "source": [
507 | "### Accepting arguments with decorator functions"
508 | ]
509 | },
510 | {
511 | "cell_type": "code",
512 | "execution_count": 11,
513 | "metadata": {
514 | "application/vnd.databricks.v1+cell": {
515 | "inputWidgets": {},
516 | "nuid": "310cabd3-1637-4d93-b127-beb5abb3925f",
517 | "showTitle": false,
518 | "title": ""
519 | }
520 | },
521 | "outputs": [
522 | {
523 | "name": "stdout",
524 | "output_type": "stream",
525 | "text": [
526 | "My arguments are: Barcelona, Milan\n",
527 | "Cities I love are Barcelona and Milan\n"
528 | ]
529 | }
530 | ],
531 | "source": [
532 | "def decorator_with_arguments(function):\n",
533 | " def wrapper_accepting_arguments(arg1,arg2):\n",
534 | " print(f\"My arguments are: {arg1}, {arg2}\")\n",
535 | " function(arg1,arg2)\n",
536 | " return wrapper_accepting_arguments\n",
537 | "\n",
538 | "@decorator_with_arguments\n",
539 | "def cities(city_one,city_two):\n",
540 | " print(f'Cities I love are {city_one} and {city_two}')\n",
541 | " \n",
542 | "cities('Barcelona','Milan')"
543 | ]
544 | },
545 | {
546 | "cell_type": "markdown",
547 | "metadata": {
548 | "application/vnd.databricks.v1+cell": {
549 | "inputWidgets": {},
550 | "nuid": "382e334e-3769-4c74-9ee7-38fed010db5d",
551 | "showTitle": false,
552 | "title": ""
553 | }
554 | },
555 | "source": [
556 | "### Passing arguments to the decorator"
557 | ]
558 | },
559 | {
560 | "cell_type": "code",
561 | "execution_count": 12,
562 | "metadata": {
563 | "application/vnd.databricks.v1+cell": {
564 | "inputWidgets": {},
565 | "nuid": "753ba376-da9d-4531-af18-c871314ea60a",
566 | "showTitle": false,
567 | "title": ""
568 | }
569 | },
570 | "outputs": [
571 | {
572 | "name": "stdout",
573 | "output_type": "stream",
574 | "text": [
575 | "The wrapper can access all the variables from the decorator maker: \n",
576 | " Pandas Numpy Scikit-learn from the function call: \n",
577 | " Pandas Science Tools \n",
578 | " and pass them to the decorated function\n",
579 | "This is the decorated function and it only knows about its arguments: \n",
580 | " Pandas Science Tools\n"
581 | ]
582 | }
583 | ],
584 | "source": [
585 | "def decorator_maker_with_arguments(decorator_arg1, decorator_arg2, decorator_arg3):\n",
586 | " def decorator(func):\n",
587 | " def wrapper(function_arg1, function_arg2, function_arg3) :\n",
588 | " \"This is the wrapper function\"\n",
589 | " print(f'The wrapper can access all the variables from the decorator maker: \\n\\\n",
590 | " {decorator_arg1} {decorator_arg2} {decorator_arg3} from the function call: \\n\\\n",
591 | " {function_arg1} {function_arg2} {function_arg3} \\n\\\n",
592 | " and pass them to the decorated function')\n",
593 | " \n",
594 | " return func(function_arg1, function_arg2,function_arg3)\n",
595 | "\n",
596 | " return wrapper\n",
597 | "\n",
598 | " return decorator\n",
599 | "\n",
600 | "pandas = \"Pandas\"\n",
601 | "@decorator_maker_with_arguments(pandas, \"Numpy\",\"Scikit-learn\")\n",
602 | "def decorated_function_with_arguments(function_arg1, function_arg2,function_arg3):\n",
603 | " print(f\"This is the decorated function and it only knows about its arguments: \\n\\\n",
604 | " {function_arg1} {function_arg2} {function_arg3}\")\n",
605 | "\n",
606 | "decorated_function_with_arguments(pandas, \"Science\", \"Tools\")"
607 | ]
608 | },
609 | {
610 | "cell_type": "markdown",
611 | "metadata": {
612 | "application/vnd.databricks.v1+cell": {
613 | "inputWidgets": {},
614 | "nuid": "be36c628-d969-4915-bd1e-323b00d73993",
615 | "showTitle": false,
616 | "title": ""
617 | }
618 | },
619 | "source": [
620 | "### Classes as decorators\n",
621 | "\n",
622 | "There are two ways of using decorators with classes; one can either decorate the individual methods inside the class or decorate the whole class. The below example refers to the latter.\n",
623 | "\n",
624 | "As mentioned earlier, the decorator syntax `@uppercase_decorator` is just an easier way of saying `func = uppercase_decorator(func)`. Therefore, if `uppercase_decorator` is a class, it needs to take func as an argument in its `.__init__()` method. Furthermore, the class instance needs to be callable so that it can stand in for the decorated function.\n",
625 | "\n",
626 | "For a class instance to be callable, you implement the special `.__call__()` method:\n",
627 | "\n",
628 | "The `.__init__()` method must store a reference to the function and can do any other necessary initialization. The `.__call__()` method will be called instead of the decorated function. It does essentially the same thing as the wrapper() function in our earlier examples."
629 | ]
630 | },
631 | {
632 | "cell_type": "code",
633 | "execution_count": 13,
634 | "metadata": {
635 | "application/vnd.databricks.v1+cell": {
636 | "inputWidgets": {},
637 | "nuid": "9e6fab53-3818-4eec-ac9e-ddc4beec1b75",
638 | "showTitle": false,
639 | "title": ""
640 | }
641 | },
642 | "outputs": [
643 | {
644 | "name": "stdout",
645 | "output_type": "stream",
646 | "text": [
647 | "Hello there!\n"
648 | ]
649 | }
650 | ],
651 | "source": [
652 | "class mydecorator:\n",
653 | " def __init__(self, function):\n",
654 | " self.function = function\n",
655 | " \n",
656 | " def __call__(self):\n",
657 | " \n",
658 | " # We can add some code\n",
659 | " # before function call\n",
660 | " \n",
661 | " func = self.function()\n",
662 | " \n",
663 | " # We can also add some code\n",
664 | " # after function call.\n",
665 | " return \n",
666 | " \n",
667 | " \n",
668 | "# adding class decorator to the function\n",
669 | "@mydecorator\n",
670 | "def function():\n",
671 | " print(\"Hello there!\")\n",
672 | "\n",
673 | "function()"
674 | ]
675 | },
676 | {
677 | "cell_type": "markdown",
678 | "metadata": {
679 | "application/vnd.databricks.v1+cell": {
680 | "inputWidgets": {},
681 | "nuid": "9686aef0-98dd-460e-b740-faa95ed11f45",
682 | "showTitle": false,
683 | "title": ""
684 | }
685 | },
686 | "source": [
687 | "Implementing the earlier example by using classes as decorators"
688 | ]
689 | },
690 | {
691 | "cell_type": "code",
692 | "execution_count": 14,
693 | "metadata": {
694 | "application/vnd.databricks.v1+cell": {
695 | "inputWidgets": {},
696 | "nuid": "58a37d0a-fbbc-4c0f-a03c-534104304258",
697 | "showTitle": false,
698 | "title": ""
699 | }
700 | },
701 | "outputs": [
702 | {
703 | "data": {
704 | "text/plain": [
705 | "'HELLO THERE!'"
706 | ]
707 | },
708 | "execution_count": 14,
709 | "metadata": {},
710 | "output_type": "execute_result"
711 | }
712 | ],
713 | "source": [
714 | "class uppercase_decorator:\n",
715 | " def __init__(self, function):\n",
716 | " self.function = function\n",
717 | " \n",
718 | " def __call__(self):\n",
719 | " func = self.function()\n",
720 | " make_uppercase = func.upper()\n",
721 | " return make_uppercase\n",
722 | " \n",
723 | " \n",
724 | "# adding class decorator to the function\n",
725 | "@uppercase_decorator\n",
726 | "def function():\n",
727 | " return \"Hello there!\"\n",
728 | "\n",
729 | "function()"
730 | ]
731 | },
732 | {
733 | "cell_type": "code",
734 | "execution_count": 15,
735 | "metadata": {
736 | "application/vnd.databricks.v1+cell": {
737 | "inputWidgets": {},
738 | "nuid": "0f379f89-7601-4d5c-9252-808cf009b458",
739 | "showTitle": false,
740 | "title": ""
741 | }
742 | },
743 | "outputs": [],
744 | "source": [
745 | "class mydecorator:\n",
746 | " def __init__(self,func):\n",
747 | " self.func = func\n",
748 | " \n",
749 | " def __call__(self,*args,**kwargs):\n",
750 | " self.func(*args,**kwargs)\n",
751 | "\n",
752 | "\n",
753 | "@mydecorator\n",
754 | "def function(name, message ='Hello'):\n",
755 | " return(f\"{message}, {name}\")\n",
756 | "\n",
757 | "function(\"geeks_for_geeks\", \"hello\")"
758 | ]
759 | },
760 | {
761 | "cell_type": "markdown",
762 | "metadata": {
763 | "application/vnd.databricks.v1+cell": {
764 | "inputWidgets": {},
765 | "nuid": "44d5f087-9271-4843-a907-d43cc483a378",
766 | "showTitle": false,
767 | "title": ""
768 | }
769 | },
770 | "source": [
771 | "### Decorating classes\n",
772 | "\n",
773 | "Three of the most common Python decorators are used for decorating class methods:\n",
774 | "- `@property` is used to create property attributes that can only be accessed through its getter, setter, and deleter methods.\n",
775 | "\n",
776 | "- `@staticmethod` and `@classmethod` are used to define class methods that are not connected to particular instances of the class. Static methods don’t require an argument, while class methods take the class as an argument."
777 | ]
778 | },
779 | {
780 | "cell_type": "code",
781 | "execution_count": 16,
782 | "metadata": {
783 | "application/vnd.databricks.v1+cell": {
784 | "inputWidgets": {},
785 | "nuid": "3deb212b-4785-4885-9d7d-3ac9104bd51e",
786 | "showTitle": false,
787 | "title": ""
788 | }
789 | },
790 | "outputs": [
791 | {
792 | "name": "stdout",
793 | "output_type": "stream",
794 | "text": [
795 | "39825.75\n",
796 | "98621.75\n"
797 | ]
798 | }
799 | ],
800 | "source": [
801 | "class Account:\n",
802 | " def __init__(self, balance):\n",
803 | " self._balance = balance\n",
804 | " @property\n",
805 | " def balance(self):\n",
806 | " \"\"\"Gets balance\"\"\"\n",
807 | " return self._balance\n",
808 | " \n",
809 | " @balance.setter\n",
810 | " def balance(self, value):\n",
811 | " \"\"\"Set balance, raise error if negative\"\"\"\n",
812 | " if value >= 0:\n",
813 | " self._balance = value\n",
814 | " else:\n",
815 | " raise ValueError(\"balance must be positive\")\n",
816 | " \n",
817 | " @classmethod\n",
818 | " def new_account(cls):\n",
819 | " \"\"\"Returns a new account with 100.00 balance\"\"\"\n",
820 | " return cls(100.00)\n",
821 | " \n",
822 | " @staticmethod\n",
823 | " def interest():\n",
824 | " \"\"\"The interest rate\"\"\"\n",
825 | " return 5.25\n",
826 | "\n",
827 | "\n",
828 | "acc = Account(39825.75)\n",
829 | "print(acc.balance)\n",
830 | "acc.balance = 98621.75\n",
831 | "print(acc.balance)"
832 | ]
833 | }
834 | ],
835 | "metadata": {
836 | "anaconda-cloud": {},
837 | "application/vnd.databricks.v1+notebook": {
838 | "dashboards": [],
839 | "language": "python",
840 | "notebookMetadata": {
841 | "pythonIndentUnit": 2
842 | },
843 | "notebookName": "Python_Part5",
844 | "notebookOrigID": 3085993468102599,
845 | "widgets": {}
846 | },
847 | "kernelspec": {
848 | "display_name": "Python 3",
849 | "language": "python",
850 | "name": "python3"
851 | },
852 | "language_info": {
853 | "codemirror_mode": {
854 | "name": "ipython",
855 | "version": 3
856 | },
857 | "file_extension": ".py",
858 | "mimetype": "text/x-python",
859 | "name": "python",
860 | "nbconvert_exporter": "python",
861 | "pygments_lexer": "ipython3",
862 | "version": "3.7.3"
863 | }
864 | },
865 | "nbformat": 4,
866 | "nbformat_minor": 1
867 | }
868 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Python_Starter_Toolkit
2 |
3 | Python toolkit to get started with data science and machine learning notebooks
4 |
5 | When I started learning python, I used to get lost in what concepts to learn in python language, especially coming from a non programming background. This repository is aimed to help learners from non computer science background to know what key concepts of python progamming language is important for **data science** and **machine learning** projects.
6 |
7 | This repository will have a series of notebooks to get learn basic python concepts necessary to get started with data science and machine learning projects. In future, I will be adding notebooks for learning key python libraries - pandas and numpy.
8 |
9 | Some of the examples in these notebooks have been referenced from [learnbyexample](https://www.learnbyexample.org/python/) and [real python](https://realpython.com/) which are very good resources to learn python.
10 |
11 | Python:
12 |
13 | 1. Part 1
14 | - Math Operators
15 | - Variables
16 | - Flow Control
17 | - Boolean Operators
18 | - List
19 | - Dictionary
20 | 2. Part 2
21 | - Dictionary continued
22 | - Comprehension
23 |
24 | 3. Part 3
25 | - Strings
26 | - Python escape sequences
27 | - String Slicing
28 | - If-Else-Elif
29 | - Loops - For & While
30 |
31 | 4. Part 4
32 | - OOPS (Classes, objects and methods)
33 | - Inheritance
34 | - super()
35 | 5. Functions
36 | - functions using def
37 | - lambda functions
38 | - lambda functions with map, filter and reduce
39 |
40 | 6. Decorators
41 | - Functions as first-class objects
42 | - Creating Decorators
43 | - Decorator with arguments
44 | - Classes as decorators/Decorators as classes
45 |
46 | Pandas
47 |
48 | 1. Part 1
49 | - Series, Dataframes
50 | - Basic methods(head, tail, unique, etc.)
51 | - Filtering
52 | - Pivoting
53 |
54 | 2. Part 2
55 | - Concat/Append
56 | - Merge
57 | - Groupby
58 |
59 | References:
60 | 1. https://www.learnbyexample.org/python/
61 | 2. https://realpython.com/
62 | 3. https://medium.com/analytics-vidhya/a-tip-a-day-python-tip-5-pandas-concat-append-dev-skrol-18e4950cc8cc
63 | 4. https://jakevdp.github.io/PythonDataScienceHandbook/03.07-merge-and-join.html
64 |
65 |
66 |
--------------------------------------------------------------------------------