├── README.md
└── 8_Essential_Python_Tips.ipynb
/README.md:
--------------------------------------------------------------------------------
1 | # 8-Essential-Python-Tips-Every-Developer-Should-Know
--------------------------------------------------------------------------------
/8_Essential_Python_Tips.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "id": "0cd25c91",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": []
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "id": "2426fa31",
14 | "metadata": {},
15 | "source": [
16 | "# 🌟 Essential Python Functions 🌟\n",
17 | "\n",
18 | "## Enhance Your Coding Skills with These Key Python Functions\n",
19 | "\n",
20 | "\n",
21 | "\n",
22 | "## 🔍 Key Python Functions Overview\n",
23 | "\n",
24 | "Here's a quick overview of some key Python functions:\n",
25 | "\n",
26 | "- **`all()`**: ✅ Verify if all elements in an iterable are `True`.\n",
27 | "- **`any()`**: ❓ Check if any element in an iterable is `True`.\n",
28 | "- **`zip()`**: 🔗 Combine multiple iterables into a single iterable.\n",
29 | "- **`enumerate()`**: 🔢 Track indices while iterating through sequences.\n",
30 | "- **`reversed()`**: 🔄 Reverse the order of elements in a sequence.\n",
31 | "- **`min()`**: 📉 Find the smallest item in a sequence.\n",
32 | "- **`max()`**: 📈 Determine the largest item in a sequence.\n",
33 | "- **`sorted()`**: 🗂️ Sort iterables in ascending or descending order.\n",
34 | "\n",
35 | "---\n",
36 | "\n",
37 | "## In-Depth Examples \n",
38 | "---\n",
39 | "\n",
40 | "### Using `all()` to Validate RGB Values\n",
41 | "\n",
42 | "#### Function Description\n",
43 | "- The `all()` function checks if all elements in an iterable (like a list or tuple) are `True`.\n",
44 | "- If any element is `False`, it returns `False`.\n",
45 | "- Otherwise, it returns `True`.\n",
46 | "\n",
47 | "#### Implementing `valid_rgb()`\n",
48 | "- We'll implement a function `valid_rgb()` to check if RGB values are within the valid range (0-255).\n",
49 | "- Different implementations for this function will be shown.\n",
50 | "\n",
51 | "\n",
52 | "---"
53 | ]
54 | },
55 | {
56 | "cell_type": "code",
57 | "execution_count": null,
58 | "id": "4c8c5ab7",
59 | "metadata": {},
60 | "outputs": [],
61 | "source": []
62 | },
63 | {
64 | "cell_type": "code",
65 | "execution_count": null,
66 | "id": "937bf3b9",
67 | "metadata": {},
68 | "outputs": [],
69 | "source": []
70 | },
71 | {
72 | "cell_type": "markdown",
73 | "id": "dbd5d3ad",
74 | "metadata": {},
75 | "source": [
76 | "### First Implementation : Using a for Loop\n"
77 | ]
78 | },
79 | {
80 | "cell_type": "code",
81 | "execution_count": 1,
82 | "id": "ad7eb8dd",
83 | "metadata": {},
84 | "outputs": [],
85 | "source": [
86 | "def valid_rgb(rgb):\n",
87 | " for val in rgb:\n",
88 | " if not 0 <= val <= 255:\n",
89 | " return False\n",
90 | " return True"
91 | ]
92 | },
93 | {
94 | "cell_type": "markdown",
95 | "id": "0a011888",
96 | "metadata": {},
97 | "source": [
98 | "### Explanation\n",
99 | "\n",
100 | "- This implementation uses a `for` loop to iterate through each value in the `rgb` tuple.\n",
101 | "- It checks if each value is within the range 0-255.\n",
102 | "- If any value is outside this range, it returns `False`.\n",
103 | "- If all values are within the range, it returns `True`.\n"
104 | ]
105 | },
106 | {
107 | "cell_type": "code",
108 | "execution_count": null,
109 | "id": "e45a35b7",
110 | "metadata": {},
111 | "outputs": [],
112 | "source": []
113 | },
114 | {
115 | "cell_type": "code",
116 | "execution_count": null,
117 | "id": "a334463e",
118 | "metadata": {},
119 | "outputs": [],
120 | "source": []
121 | },
122 | {
123 | "cell_type": "markdown",
124 | "id": "ca4481a4",
125 | "metadata": {},
126 | "source": [
127 | "## Second Implementation: Using a while Loop\n"
128 | ]
129 | },
130 | {
131 | "cell_type": "code",
132 | "execution_count": 2,
133 | "id": "2f4d3bda",
134 | "metadata": {},
135 | "outputs": [],
136 | "source": [
137 | "def valid_rgb(rgb):\n",
138 | " i = 0\n",
139 | " while i < len(rgb):\n",
140 | " if not 0 <= rgb[i] <= 255:\n",
141 | " return False\n",
142 | " i += 1\n",
143 | " return True"
144 | ]
145 | },
146 | {
147 | "cell_type": "markdown",
148 | "id": "eeee6e26",
149 | "metadata": {},
150 | "source": [
151 | "### Explanation\n",
152 | "\n",
153 | "- This implementation uses a `while` loop to achieve the same functionality as the `for` loop version.\n",
154 | "- It iterates through each value in the `rgb` tuple, checking if it lies within the 0-255 range.\n",
155 | "- The loop continues until all values are checked or a value outside the range is found.\n"
156 | ]
157 | },
158 | {
159 | "cell_type": "code",
160 | "execution_count": null,
161 | "id": "ba63598a",
162 | "metadata": {},
163 | "outputs": [],
164 | "source": []
165 | },
166 | {
167 | "cell_type": "code",
168 | "execution_count": null,
169 | "id": "ad7bab6f",
170 | "metadata": {},
171 | "outputs": [],
172 | "source": []
173 | },
174 | {
175 | "cell_type": "markdown",
176 | "id": "3fc27b63",
177 | "metadata": {},
178 | "source": [
179 | "## Third Implementation: Using List Comprehension"
180 | ]
181 | },
182 | {
183 | "cell_type": "code",
184 | "execution_count": 3,
185 | "id": "2a92858f",
186 | "metadata": {},
187 | "outputs": [],
188 | "source": [
189 | "def valid_rgb(rgb):\n",
190 | " return all([0 <= val <= 255 for val in rgb])"
191 | ]
192 | },
193 | {
194 | "cell_type": "markdown",
195 | "id": "042f6e71",
196 | "metadata": {},
197 | "source": [
198 | "### Explanation\n",
199 | "\n",
200 | "- This implementation uses list comprehension along with the `all()` function to check if all values in the `rgb` tuple are within the range 0-255.\n",
201 | "- List comprehension creates a list of boolean values (`True` or `False`) for each check.\n",
202 | "- The `all()` function ensures all values are `True`."
203 | ]
204 | },
205 | {
206 | "cell_type": "code",
207 | "execution_count": null,
208 | "id": "6d511e52",
209 | "metadata": {},
210 | "outputs": [],
211 | "source": []
212 | },
213 | {
214 | "cell_type": "code",
215 | "execution_count": null,
216 | "id": "98d40d81",
217 | "metadata": {},
218 | "outputs": [],
219 | "source": []
220 | },
221 | {
222 | "cell_type": "markdown",
223 | "id": "9f9f8e76",
224 | "metadata": {},
225 | "source": [
226 | "## Fourth Implementation: Using a Generator Expression"
227 | ]
228 | },
229 | {
230 | "cell_type": "code",
231 | "execution_count": 4,
232 | "id": "cb88c766",
233 | "metadata": {},
234 | "outputs": [],
235 | "source": [
236 | "def valid_rgb(rgb):\n",
237 | " return all(0 <= val <= 255 for val in rgb)"
238 | ]
239 | },
240 | {
241 | "cell_type": "markdown",
242 | "id": "6ce100bd",
243 | "metadata": {},
244 | "source": [
245 | "### Explanation\n",
246 | "\n",
247 | "- This implementation is similar to the list comprehension method but uses a generator expression.\n",
248 | "- The `all()` function processes each value one by one, which is more memory efficient than creating a full list of boolean values.\n"
249 | ]
250 | },
251 | {
252 | "cell_type": "code",
253 | "execution_count": null,
254 | "id": "99d3448c",
255 | "metadata": {},
256 | "outputs": [],
257 | "source": []
258 | },
259 | {
260 | "cell_type": "markdown",
261 | "id": "28cfb7cd",
262 | "metadata": {},
263 | "source": [
264 | "## ✅ Validation of Test Cases"
265 | ]
266 | },
267 | {
268 | "cell_type": "code",
269 | "execution_count": 5,
270 | "id": "0ff0d701",
271 | "metadata": {},
272 | "outputs": [
273 | {
274 | "name": "stdout",
275 | "output_type": "stream",
276 | "text": [
277 | "- Testing Line 1: (23, 4, 225) - result=True, expected=True\n",
278 | "\n",
279 | "- Testing Line 2: (255, 255, 255) - result=True, expected=True\n",
280 | "\n",
281 | "- Testing Line 3: (300, 255, 200) - result=False, expected=False\n",
282 | "\n",
283 | "- Testing Line 4: (250, 270, 190) - result=False, expected=False\n",
284 | "\n",
285 | "- Testing Line 5: (250, 103, 490) - result=False, expected=False\n",
286 | "\n",
287 | "Test cases validation completed..🎯🥳\n"
288 | ]
289 | }
290 | ],
291 | "source": [
292 | "test_cases = [\n",
293 | " ((23, 4, 225), True), \n",
294 | " ((255, 255, 255), True), \n",
295 | " ((300, 255, 200), False),\n",
296 | " ((250, 270, 190), False),\n",
297 | " ((250, 103, 490), False)\n",
298 | "]\n",
299 | "\n",
300 | "# Validate test cases using print with line numbers\n",
301 | "for i, (rgb, expected) in enumerate(test_cases, start=1):\n",
302 | " result = valid_rgb(rgb)\n",
303 | " print(f\"- Testing Line {i}: {rgb} - result={result}, expected={expected}\")\n",
304 | " if result != expected:\n",
305 | " print(f\"Line {i}: Test case {rgb} failed: Expected {expected} but got {result}\")\n",
306 | " else:\n",
307 | " print(\"\")\n",
308 | "\n",
309 | "print('Test cases validation completed..🎯🥳')"
310 | ]
311 | },
312 | {
313 | "cell_type": "code",
314 | "execution_count": null,
315 | "id": "f32e18ba",
316 | "metadata": {},
317 | "outputs": [],
318 | "source": []
319 | },
320 | {
321 | "cell_type": "code",
322 | "execution_count": 6,
323 | "id": "e3dddf7a",
324 | "metadata": {},
325 | "outputs": [
326 | {
327 | "data": {
328 | "text/plain": [
329 | "False"
330 | ]
331 | },
332 | "execution_count": 6,
333 | "metadata": {},
334 | "output_type": "execute_result"
335 | }
336 | ],
337 | "source": [
338 | "all(['Ronaldo','16','AA',''])"
339 | ]
340 | },
341 | {
342 | "cell_type": "code",
343 | "execution_count": 7,
344 | "id": "78b25eb2",
345 | "metadata": {},
346 | "outputs": [
347 | {
348 | "data": {
349 | "text/plain": [
350 | "True"
351 | ]
352 | },
353 | "execution_count": 7,
354 | "metadata": {},
355 | "output_type": "execute_result"
356 | }
357 | ],
358 | "source": [
359 | "all(['Vini','16','AA','Y5'])"
360 | ]
361 | },
362 | {
363 | "cell_type": "markdown",
364 | "id": "ad9201c7",
365 | "metadata": {},
366 | "source": [
367 | "## 📋 Conclusion\n",
368 | "\n",
369 | "- Understanding different ways to implement and validate functions in Python is crucial for writing robust and efficient code.\n",
370 | "- Using `all()` and exploring various implementations enhances our ability to handle different scenarios in coding.\n"
371 | ]
372 | },
373 | {
374 | "cell_type": "code",
375 | "execution_count": null,
376 | "id": "9a493ce1",
377 | "metadata": {},
378 | "outputs": [],
379 | "source": []
380 | },
381 | {
382 | "cell_type": "code",
383 | "execution_count": null,
384 | "id": "a21b2d87",
385 | "metadata": {},
386 | "outputs": [],
387 | "source": []
388 | },
389 | {
390 | "cell_type": "markdown",
391 | "id": "27c7c600",
392 | "metadata": {},
393 | "source": [
394 | "### Using `any()` to Check for Digits\n",
395 | "\n",
396 | "#### Function Description\n",
397 | "- The `any()` function checks if any element in an iterable is `True`.\n",
398 | "- If any element is `True`, it returns `True`.\n",
399 | "- Otherwise, it returns `False`.\n",
400 | "\n",
401 | "#### Implementing `contains_digit()`\n",
402 | "- We'll implement a function `contains_digit()` to check if a string contains any digit.\n"
403 | ]
404 | },
405 | {
406 | "cell_type": "code",
407 | "execution_count": null,
408 | "id": "4979a253",
409 | "metadata": {},
410 | "outputs": [],
411 | "source": []
412 | },
413 | {
414 | "cell_type": "markdown",
415 | "id": "faaf2f7c",
416 | "metadata": {},
417 | "source": [
418 | "## First Implementation: Using a for Loop\n"
419 | ]
420 | },
421 | {
422 | "cell_type": "code",
423 | "execution_count": 8,
424 | "id": "d1fd377f",
425 | "metadata": {},
426 | "outputs": [],
427 | "source": [
428 | "def contains_digit(input_user):\n",
429 | " for char in input_user:\n",
430 | " if char.isdigit():\n",
431 | " return True\n",
432 | " return False"
433 | ]
434 | },
435 | {
436 | "cell_type": "markdown",
437 | "id": "e6f935ef",
438 | "metadata": {},
439 | "source": [
440 | "### Explanation\n",
441 | "\n",
442 | "- This implementation uses a `for` loop to iterate through each character in the `input_user` string.\n",
443 | "- It checks if any character is a digit using the `isdigit()` method.\n",
444 | "- If a digit is found, it returns `True`.\n",
445 | "- If no digits are found, it returns `False`."
446 | ]
447 | },
448 | {
449 | "cell_type": "code",
450 | "execution_count": null,
451 | "id": "d7cc6633",
452 | "metadata": {},
453 | "outputs": [],
454 | "source": []
455 | },
456 | {
457 | "cell_type": "code",
458 | "execution_count": null,
459 | "id": "855c92b9",
460 | "metadata": {},
461 | "outputs": [],
462 | "source": []
463 | },
464 | {
465 | "cell_type": "markdown",
466 | "id": "ecd815df",
467 | "metadata": {},
468 | "source": [
469 | "## Second Implementation: Using any() with a Generator Expression"
470 | ]
471 | },
472 | {
473 | "cell_type": "code",
474 | "execution_count": 9,
475 | "id": "98896e54",
476 | "metadata": {},
477 | "outputs": [],
478 | "source": [
479 | "def contains_digit(input_user):\n",
480 | " return any(char.isdigit() for char in input_user)"
481 | ]
482 | },
483 | {
484 | "cell_type": "markdown",
485 | "id": "9777f0c4",
486 | "metadata": {},
487 | "source": [
488 | "### Explanation\n",
489 | "\n",
490 | "- This implementation uses the `any()` function combined with a generator expression.\n",
491 | "- The generator expression checks each character in the `input_user` string to see if it's a digit.\n",
492 | "- The `any()` function returns `True` as soon as it finds a digit, making this method more efficient."
493 | ]
494 | },
495 | {
496 | "cell_type": "code",
497 | "execution_count": null,
498 | "id": "ab83438c",
499 | "metadata": {},
500 | "outputs": [],
501 | "source": []
502 | },
503 | {
504 | "cell_type": "markdown",
505 | "id": "f7004746",
506 | "metadata": {},
507 | "source": [
508 | "## ✅ Validation of Test Cases"
509 | ]
510 | },
511 | {
512 | "cell_type": "code",
513 | "execution_count": 10,
514 | "id": "9d0edfb0",
515 | "metadata": {},
516 | "outputs": [],
517 | "source": [
518 | "# Test cases for contains_digit\n",
519 | "digit_test_cases = [\n",
520 | " ('8Essential_Python', True),\n",
521 | " ('Hello_World123', True),\n",
522 | " ('Data', False)]"
523 | ]
524 | },
525 | {
526 | "cell_type": "code",
527 | "execution_count": null,
528 | "id": "2e4d8e55",
529 | "metadata": {},
530 | "outputs": [],
531 | "source": []
532 | },
533 | {
534 | "cell_type": "code",
535 | "execution_count": 11,
536 | "id": "c91d1534",
537 | "metadata": {},
538 | "outputs": [
539 | {
540 | "name": "stdout",
541 | "output_type": "stream",
542 | "text": [
543 | "- Testing Line 1: 8Essential_Python - result=True, expected=True\n",
544 | "\n",
545 | "- Testing Line 2: Hello_World123 - result=True, expected=True\n",
546 | "\n",
547 | "- Testing Line 3: Data - result=False, expected=False\n",
548 | "\n",
549 | "Test cases validation completed..🎯🥳\n"
550 | ]
551 | }
552 | ],
553 | "source": [
554 | "for i, (input_user, expected) in enumerate(digit_test_cases, start=1):\n",
555 | " result = contains_digit(input_user)\n",
556 | " print(f\"- Testing Line {i}: {input_user} - result={result}, expected={expected}\")\n",
557 | " if result != expected:\n",
558 | " print(f\"Line {i}: Test case {input_user} failed: Expected {expected} but got {result}\")\n",
559 | " else:\n",
560 | " print(\"\")\n",
561 | "\n",
562 | "print('Test cases validation completed..🎯🥳')"
563 | ]
564 | },
565 | {
566 | "cell_type": "code",
567 | "execution_count": null,
568 | "id": "f0db95d2",
569 | "metadata": {},
570 | "outputs": [],
571 | "source": []
572 | },
573 | {
574 | "cell_type": "code",
575 | "execution_count": 12,
576 | "id": "6b63cc36",
577 | "metadata": {},
578 | "outputs": [
579 | {
580 | "data": {
581 | "text/plain": [
582 | "True"
583 | ]
584 | },
585 | "execution_count": 12,
586 | "metadata": {},
587 | "output_type": "execute_result"
588 | }
589 | ],
590 | "source": [
591 | "any(['Ronaldo','16','AA',''])"
592 | ]
593 | },
594 | {
595 | "cell_type": "code",
596 | "execution_count": 13,
597 | "id": "ed40da34",
598 | "metadata": {},
599 | "outputs": [
600 | {
601 | "data": {
602 | "text/plain": [
603 | "True"
604 | ]
605 | },
606 | "execution_count": 13,
607 | "metadata": {},
608 | "output_type": "execute_result"
609 | }
610 | ],
611 | "source": [
612 | "any(['Vini','16','AA','Y5'])"
613 | ]
614 | },
615 | {
616 | "cell_type": "code",
617 | "execution_count": 14,
618 | "id": "c6f638cd",
619 | "metadata": {},
620 | "outputs": [
621 | {
622 | "data": {
623 | "text/plain": [
624 | "False"
625 | ]
626 | },
627 | "execution_count": 14,
628 | "metadata": {},
629 | "output_type": "execute_result"
630 | }
631 | ],
632 | "source": [
633 | "any([0,''])"
634 | ]
635 | },
636 | {
637 | "cell_type": "code",
638 | "execution_count": 15,
639 | "id": "20ab5fc9",
640 | "metadata": {},
641 | "outputs": [
642 | {
643 | "data": {
644 | "text/plain": [
645 | "True"
646 | ]
647 | },
648 | "execution_count": 15,
649 | "metadata": {},
650 | "output_type": "execute_result"
651 | }
652 | ],
653 | "source": [
654 | "any([0,'M.Salah'])"
655 | ]
656 | },
657 | {
658 | "cell_type": "code",
659 | "execution_count": null,
660 | "id": "05c5a392",
661 | "metadata": {},
662 | "outputs": [],
663 | "source": []
664 | },
665 | {
666 | "cell_type": "markdown",
667 | "id": "86eadfbf",
668 | "metadata": {},
669 | "source": [
670 | "### 📋 Conclusion\n",
671 | "\n",
672 | "- Understanding different ways to implement and validate functions in Python is crucial for writing robust and efficient code.\n",
673 | "- By using `all()` and `any()` and exploring various implementations, we've enhanced our ability to handle different scenarios in coding.\n"
674 | ]
675 | },
676 | {
677 | "cell_type": "code",
678 | "execution_count": null,
679 | "id": "ef9bd6bc",
680 | "metadata": {},
681 | "outputs": [],
682 | "source": []
683 | },
684 | {
685 | "cell_type": "code",
686 | "execution_count": null,
687 | "id": "2548be22",
688 | "metadata": {},
689 | "outputs": [],
690 | "source": []
691 | },
692 | {
693 | "cell_type": "markdown",
694 | "id": "231c61ff",
695 | "metadata": {},
696 | "source": [
697 | "---\n",
698 | "# Comprehensive Guide to `enumerate()`\n",
699 | "\n",
700 | "The `enumerate()` function in Python is a handy tool for iterating over a sequence while keeping track of the index. Below are various ways to use `enumerate()` effectively.\n",
701 | "\n",
702 | "## Example 1: Basic Enumeration with Index\n",
703 | "\n",
704 | "Print each item in a list with its index using a traditional for loop with `range()` and `len()`.\n"
705 | ]
706 | },
707 | {
708 | "cell_type": "code",
709 | "execution_count": 16,
710 | "id": "90cf7b70",
711 | "metadata": {},
712 | "outputs": [
713 | {
714 | "name": "stdout",
715 | "output_type": "stream",
716 | "text": [
717 | "1. Egypt\n",
718 | "2. Spain\n",
719 | "3. England\n",
720 | "4. Qatar\n",
721 | "5. Saudi Arabia\n",
722 | "6. Jordan\n"
723 | ]
724 | }
725 | ],
726 | "source": [
727 | "countries = ['Egypt','Spain','England','Qatar','Saudi Arabia','Jordan']\n",
728 | "for index in range(len(countries)):\n",
729 | " print(f'{index+1}. {countries[index]}')"
730 | ]
731 | },
732 | {
733 | "cell_type": "code",
734 | "execution_count": null,
735 | "id": "d57876f2",
736 | "metadata": {},
737 | "outputs": [],
738 | "source": []
739 | },
740 | {
741 | "cell_type": "markdown",
742 | "id": "4a6c8b34",
743 | "metadata": {},
744 | "source": [
745 | "## Example 2: Direct Iteration Over the List"
746 | ]
747 | },
748 | {
749 | "cell_type": "code",
750 | "execution_count": 17,
751 | "id": "943956d4",
752 | "metadata": {},
753 | "outputs": [
754 | {
755 | "name": "stdout",
756 | "output_type": "stream",
757 | "text": [
758 | "Egypt\n",
759 | "Spain\n",
760 | "England\n",
761 | "Qatar\n",
762 | "Saudi Arabia\n",
763 | "Jordan\n"
764 | ]
765 | }
766 | ],
767 | "source": [
768 | "for country in countries:\n",
769 | " print(country)"
770 | ]
771 | },
772 | {
773 | "cell_type": "code",
774 | "execution_count": null,
775 | "id": "fbd79db0",
776 | "metadata": {},
777 | "outputs": [],
778 | "source": []
779 | },
780 | {
781 | "cell_type": "markdown",
782 | "id": "b116843e",
783 | "metadata": {},
784 | "source": [
785 | "## Example 3: enumerate() for Index and Value"
786 | ]
787 | },
788 | {
789 | "cell_type": "code",
790 | "execution_count": 18,
791 | "id": "525fca70",
792 | "metadata": {},
793 | "outputs": [
794 | {
795 | "name": "stdout",
796 | "output_type": "stream",
797 | "text": [
798 | "1. Egypt\n",
799 | "2. Spain\n",
800 | "3. England\n",
801 | "4. Qatar\n",
802 | "5. Saudi Arabia\n",
803 | "6. Jordan\n"
804 | ]
805 | }
806 | ],
807 | "source": [
808 | "for index, country in enumerate(countries, start=1):\n",
809 | " print(f'{index}. {country}')"
810 | ]
811 | },
812 | {
813 | "cell_type": "code",
814 | "execution_count": null,
815 | "id": "8d057ef8",
816 | "metadata": {},
817 | "outputs": [],
818 | "source": []
819 | },
820 | {
821 | "cell_type": "markdown",
822 | "id": "4b7adf19",
823 | "metadata": {},
824 | "source": [
825 | "## Example 4: Tuple Output from enumerate()"
826 | ]
827 | },
828 | {
829 | "cell_type": "code",
830 | "execution_count": 19,
831 | "id": "d164675f",
832 | "metadata": {},
833 | "outputs": [
834 | {
835 | "name": "stdout",
836 | "output_type": "stream",
837 | "text": [
838 | "(1, 'Egypt')\n",
839 | "(2, 'Spain')\n",
840 | "(3, 'England')\n",
841 | "(4, 'Qatar')\n",
842 | "(5, 'Saudi Arabia')\n",
843 | "(6, 'Jordan')\n"
844 | ]
845 | }
846 | ],
847 | "source": [
848 | "for item in enumerate(countries, start=1):\n",
849 | " print(item)"
850 | ]
851 | },
852 | {
853 | "cell_type": "code",
854 | "execution_count": null,
855 | "id": "1da172bb",
856 | "metadata": {},
857 | "outputs": [],
858 | "source": []
859 | },
860 | {
861 | "cell_type": "code",
862 | "execution_count": null,
863 | "id": "a6c25ac7",
864 | "metadata": {},
865 | "outputs": [],
866 | "source": []
867 | },
868 | {
869 | "cell_type": "markdown",
870 | "id": "56b8269b",
871 | "metadata": {},
872 | "source": [
873 | "# In-Depth Examples of `zip()` and `enumerate()`\n",
874 | "\n",
875 | "## Example 1: Basic Use of `zip()`\n",
876 | "\n",
877 | "The `zip()` function pairs elements from two or more lists together. This can be useful for creating tuples of related items.\n"
878 | ]
879 | },
880 | {
881 | "cell_type": "code",
882 | "execution_count": 20,
883 | "id": "deffad17",
884 | "metadata": {},
885 | "outputs": [
886 | {
887 | "name": "stdout",
888 | "output_type": "stream",
889 | "text": [
890 | "The Capital of Egypt is Cairo\n",
891 | "The Capital of Spain is Madrid\n",
892 | "The Capital of England is London\n",
893 | "The Capital of Qatar is Doha\n",
894 | "The Capital of Saudi Arabia is Riyadh\n",
895 | "The Capital of Jordan is Amman\n"
896 | ]
897 | }
898 | ],
899 | "source": [
900 | "countries = ['Egypt', 'Spain', 'England', 'Qatar', 'Saudi Arabia', 'Jordan']\n",
901 | "capitals = ['Cairo', 'Madrid', 'London', 'Doha', 'Riyadh', 'Amman']\n",
902 | "\n",
903 | "\n",
904 | "for country, capital in zip(countries, capitals):\n",
905 | " print(f'The Capital of {country} is {capital}')"
906 | ]
907 | },
908 | {
909 | "cell_type": "code",
910 | "execution_count": null,
911 | "id": "2096b370",
912 | "metadata": {},
913 | "outputs": [],
914 | "source": []
915 | },
916 | {
917 | "cell_type": "code",
918 | "execution_count": null,
919 | "id": "5305ab9a",
920 | "metadata": {},
921 | "outputs": [],
922 | "source": []
923 | },
924 | {
925 | "cell_type": "markdown",
926 | "id": "c14e497b",
927 | "metadata": {},
928 | "source": [
929 | "## Example 2: Handling Unequal Length Lists\n",
930 | "\n",
931 | "When the lists are of different lengths, zip() stops at the end of the shortest list. To handle this situation, use zip_longest() from the itertools module to fill in missing values."
932 | ]
933 | },
934 | {
935 | "cell_type": "code",
936 | "execution_count": 21,
937 | "id": "2bec70d7",
938 | "metadata": {},
939 | "outputs": [
940 | {
941 | "name": "stdout",
942 | "output_type": "stream",
943 | "text": [
944 | "The capital of Egypt is Cairo\n",
945 | "The capital of Spain is Madrid\n",
946 | "The capital of England is London\n",
947 | "The capital of Qatar is Doha\n",
948 | "The capital of Saudi Arabia is Unknown\n",
949 | "The capital of Jordan is Unknown\n"
950 | ]
951 | }
952 | ],
953 | "source": [
954 | "from itertools import zip_longest\n",
955 | "\n",
956 | "countries = ['Egypt', 'Spain', 'England', 'Qatar', 'Saudi Arabia', 'Jordan']\n",
957 | "capitals = ['Cairo', 'Madrid', 'London', 'Doha'] # Missing some capitals\n",
958 | "\n",
959 | "\n",
960 | "for country, capital in zip_longest(countries, capitals, fillvalue='Unknown'):\n",
961 | " print(f'The capital of {country} is {capital}')"
962 | ]
963 | },
964 | {
965 | "cell_type": "code",
966 | "execution_count": null,
967 | "id": "5e61ccae",
968 | "metadata": {},
969 | "outputs": [],
970 | "source": []
971 | },
972 | {
973 | "cell_type": "code",
974 | "execution_count": null,
975 | "id": "0630dab0",
976 | "metadata": {},
977 | "outputs": [],
978 | "source": []
979 | },
980 | {
981 | "cell_type": "code",
982 | "execution_count": 22,
983 | "id": "59e74d96",
984 | "metadata": {},
985 | "outputs": [
986 | {
987 | "name": "stdout",
988 | "output_type": "stream",
989 | "text": [
990 | "The Capital of Egypt is Cairo\n",
991 | "The Capital of Spain is Madrid\n",
992 | "The Capital of England is London\n",
993 | "The Capital of Qatar is Doha\n"
994 | ]
995 | }
996 | ],
997 | "source": [
998 | "countries = ['Egypt', 'Spain', 'England', 'Qatar', 'Saudi Arabia', 'Jordan']\n",
999 | "capitals = ['Cairo', 'Madrid', 'London', 'Doha']\n",
1000 | "\n",
1001 | "for country , capital in zip(countries,capitals):\n",
1002 | " print(f'The Capital of {country} is {capital}')"
1003 | ]
1004 | },
1005 | {
1006 | "cell_type": "code",
1007 | "execution_count": null,
1008 | "id": "3852ceef",
1009 | "metadata": {},
1010 | "outputs": [],
1011 | "source": []
1012 | },
1013 | {
1014 | "cell_type": "code",
1015 | "execution_count": null,
1016 | "id": "9a7a27fc",
1017 | "metadata": {},
1018 | "outputs": [],
1019 | "source": []
1020 | },
1021 | {
1022 | "cell_type": "markdown",
1023 | "id": "30d6736d",
1024 | "metadata": {},
1025 | "source": [
1026 | "---------"
1027 | ]
1028 | },
1029 | {
1030 | "cell_type": "markdown",
1031 | "id": "849426ff",
1032 | "metadata": {},
1033 | "source": [
1034 | "### Example 3: Creating and Unzipping Pairs"
1035 | ]
1036 | },
1037 | {
1038 | "cell_type": "code",
1039 | "execution_count": 23,
1040 | "id": "1b465046",
1041 | "metadata": {},
1042 | "outputs": [
1043 | {
1044 | "data": {
1045 | "text/plain": [
1046 | "[('Egypt', 'Cairo'),\n",
1047 | " ('Spain', 'Madrid'),\n",
1048 | " ('England', 'London'),\n",
1049 | " ('Qatar', 'Doha'),\n",
1050 | " ('Saudi Arabia', 'Riyadh'),\n",
1051 | " ('Jordan', 'Amman')]"
1052 | ]
1053 | },
1054 | "execution_count": 23,
1055 | "metadata": {},
1056 | "output_type": "execute_result"
1057 | }
1058 | ],
1059 | "source": [
1060 | "countries = ['Egypt', 'Spain', 'England', 'Qatar', 'Saudi Arabia', 'Jordan']\n",
1061 | "capitals = ['Cairo', 'Madrid', 'London', 'Doha', 'Riyadh', 'Amman']\n",
1062 | "\n",
1063 | "# Creating pairs of countries and capitals\n",
1064 | "pairs = list(zip(countries, capitals))\n",
1065 | "pairs"
1066 | ]
1067 | },
1068 | {
1069 | "cell_type": "code",
1070 | "execution_count": 24,
1071 | "id": "af09970d",
1072 | "metadata": {},
1073 | "outputs": [
1074 | {
1075 | "data": {
1076 | "text/plain": [
1077 | "('Egypt', 'Spain', 'England', 'Qatar', 'Saudi Arabia', 'Jordan')"
1078 | ]
1079 | },
1080 | "execution_count": 24,
1081 | "metadata": {},
1082 | "output_type": "execute_result"
1083 | }
1084 | ],
1085 | "source": [
1086 | "country,capital = zip(*pairs)\n",
1087 | "country"
1088 | ]
1089 | },
1090 | {
1091 | "cell_type": "code",
1092 | "execution_count": 25,
1093 | "id": "fcd9c39b",
1094 | "metadata": {},
1095 | "outputs": [
1096 | {
1097 | "data": {
1098 | "text/plain": [
1099 | "('Cairo', 'Madrid', 'London', 'Doha', 'Riyadh', 'Amman')"
1100 | ]
1101 | },
1102 | "execution_count": 25,
1103 | "metadata": {},
1104 | "output_type": "execute_result"
1105 | }
1106 | ],
1107 | "source": [
1108 | "capital"
1109 | ]
1110 | },
1111 | {
1112 | "cell_type": "markdown",
1113 | "id": "7bbbb6ed",
1114 | "metadata": {},
1115 | "source": [
1116 | "------"
1117 | ]
1118 | },
1119 | {
1120 | "cell_type": "code",
1121 | "execution_count": null,
1122 | "id": "cb161e6e",
1123 | "metadata": {},
1124 | "outputs": [],
1125 | "source": []
1126 | },
1127 | {
1128 | "cell_type": "markdown",
1129 | "id": "01d4b9cb",
1130 | "metadata": {},
1131 | "source": [
1132 | "# Challenge: `enumerate()` and `zip()`\n",
1133 | "\n",
1134 | "## Births in England and Wales (Office for National Statistics)\n",
1135 | "\n",
1136 | "In this challenge, you're given the number of births in England and Wales from 2010 to 2019. The list `year` contains all the years from 2010 to 2019, and the list `birth` contains the number of births for each corresponding year.\n",
1137 | "\n",
1138 | "Your task is to return a list of tuples where each tuple contains the year, the number of births, and the running average of births up to that year.\n",
1139 | "\n",
1140 | "### Explanation of Running Average\n",
1141 | "- **For 2010**: The running average is the number of births in 2010.\n",
1142 | "- **For 2011**: The running average is the average number of births in 2010 and 2011.\n",
1143 | "- This pattern continues, with each year's running average being the average number of births from 2010 up to that year.\n",
1144 | "\n",
1145 | "
\n",
1146 | " \n",
1147 | " \n",
1148 | " | Year | \n",
1149 | " Number Of Births | \n",
1150 | " Running Average | \n",
1151 | "
\n",
1152 | " \n",
1153 | " \n",
1154 | " \n",
1155 | " | 2010 | \n",
1156 | " 723,165 | \n",
1157 | " 723,165 | \n",
1158 | "
\n",
1159 | " \n",
1160 | " | 2011 | \n",
1161 | " 723,913 | \n",
1162 | " 723,539 | \n",
1163 | "
\n",
1164 | " \n",
1165 | " | 2012 | \n",
1166 | " 729,674 | \n",
1167 | " 726,420 | \n",
1168 | "
\n",
1169 | " \n",
1170 | " | 2013 | \n",
1171 | " 698,512 | \n",
1172 | " 710,839 | \n",
1173 | "
\n",
1174 | " \n",
1175 | " | 2014 | \n",
1176 | " 695,233 | \n",
1177 | " 709,199 | \n",
1178 | "
\n",
1179 | " \n",
1180 | " | 2015 | \n",
1181 | " 697,852 | \n",
1182 | " 710,509 | \n",
1183 | "
\n",
1184 | " \n",
1185 | " | 2016 | \n",
1186 | " 696,271 | \n",
1187 | " 709,718 | \n",
1188 | "
\n",
1189 | " \n",
1190 | " | 2017 | \n",
1191 | " 679,106 | \n",
1192 | " 701,136 | \n",
1193 | "
\n",
1194 | " \n",
1195 | " | 2018 | \n",
1196 | " 657,076 | \n",
1197 | " 690,121 | \n",
1198 | "
\n",
1199 | " \n",
1200 | " | 2019 | \n",
1201 | " 640,370 | \n",
1202 | " 681,768 | \n",
1203 | "
\n",
1204 | " \n",
1205 | "
"
1206 | ]
1207 | },
1208 | {
1209 | "cell_type": "markdown",
1210 | "id": "f4510815",
1211 | "metadata": {},
1212 | "source": [
1213 | "---"
1214 | ]
1215 | },
1216 | {
1217 | "cell_type": "code",
1218 | "execution_count": 26,
1219 | "id": "ed697cc5",
1220 | "metadata": {},
1221 | "outputs": [
1222 | {
1223 | "name": "stdout",
1224 | "output_type": "stream",
1225 | "text": [
1226 | "(2010, 723165, 723165)\n",
1227 | "(2011, 723913, 723539)\n",
1228 | "(2012, 729674, 725584)\n",
1229 | "(2013, 698512, 718816)\n",
1230 | "(2014, 695233, 714099)\n",
1231 | "(2015, 697852, 711392)\n",
1232 | "(2016, 696271, 709231)\n",
1233 | "(2017, 679106, 705466)\n",
1234 | "(2018, 657076, 700089)\n",
1235 | "(2019, 640370, 694117)\n"
1236 | ]
1237 | }
1238 | ],
1239 | "source": [
1240 | "def calculate_running_average(years, births):\n",
1241 | " result = []\n",
1242 | " sum_ = 0\n",
1243 | " \n",
1244 | " # Start enumerate from 1 by specifying the start parameter\n",
1245 | " for index, (year, birth) in enumerate(zip(years, births), start=1):\n",
1246 | " sum_ += birth\n",
1247 | " running_average = round(sum_ / index)\n",
1248 | " result.append((year, birth, running_average))\n",
1249 | " \n",
1250 | " return result\n",
1251 | "\n",
1252 | "# Test the function with the provided data\n",
1253 | "years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]\n",
1254 | "births = [723_165, 723_913, 729_674, 698_512, 695_233, 697_852, 696_271, 679_106, 657_076, 640_370]\n",
1255 | "\n",
1256 | "output = calculate_running_average(years, births)\n",
1257 | "for record in output:\n",
1258 | " print(record)"
1259 | ]
1260 | },
1261 | {
1262 | "cell_type": "code",
1263 | "execution_count": null,
1264 | "id": "f05292f2",
1265 | "metadata": {},
1266 | "outputs": [],
1267 | "source": []
1268 | },
1269 | {
1270 | "cell_type": "code",
1271 | "execution_count": null,
1272 | "id": "c57fbfb1",
1273 | "metadata": {},
1274 | "outputs": [],
1275 | "source": []
1276 | },
1277 | {
1278 | "cell_type": "markdown",
1279 | "id": "414bea16",
1280 | "metadata": {},
1281 | "source": [
1282 | "# In-Depth Examples of `reversed(sequence)`\n",
1283 | "\n",
1284 | "## Understanding Sequences and Iterables\n",
1285 | "\n",
1286 | "### Sequences\n",
1287 | "A sequence is a type of iterable that has:\n",
1288 | "1. **A length**: You can get the number of elements in it.\n",
1289 | "2. **An index**: You can access elements by their position.\n",
1290 | "3. **Can be sliced**: You can get a subset of elements.\n",
1291 | "\n",
1292 | "**Examples of Sequences:**\n",
1293 | "- Strings\n",
1294 | "- Lists\n",
1295 | "- Tuples\n",
1296 | "\n",
1297 | "### Iterables That Are Not Sequences\n",
1298 | "- Dictionaries\n",
1299 | "- Sets\n",
1300 | "- Files\n",
1301 | "- Generators\n",
1302 | "\n",
1303 | "## Reversing Sequences\n",
1304 | "\n",
1305 | "### Using `reverse()`\n",
1306 | "\n",
1307 | "The `reverse()` method reverses the sequence in-place, meaning it modifies the original sequence.\n",
1308 | "\n",
1309 | "**Code Example:**"
1310 | ]
1311 | },
1312 | {
1313 | "cell_type": "code",
1314 | "execution_count": null,
1315 | "id": "fcfe41bd",
1316 | "metadata": {},
1317 | "outputs": [],
1318 | "source": []
1319 | },
1320 | {
1321 | "cell_type": "code",
1322 | "execution_count": 27,
1323 | "id": "c15a24c0",
1324 | "metadata": {},
1325 | "outputs": [],
1326 | "source": [
1327 | "countries = ['Egypt', 'Spain', 'England', 'Qatar', 'Saudi Arabia', 'Jordan']\n",
1328 | "countries.reverse()"
1329 | ]
1330 | },
1331 | {
1332 | "cell_type": "code",
1333 | "execution_count": 28,
1334 | "id": "6d36beaf",
1335 | "metadata": {},
1336 | "outputs": [
1337 | {
1338 | "data": {
1339 | "text/plain": [
1340 | "['Jordan', 'Saudi Arabia', 'Qatar', 'England', 'Spain', 'Egypt']"
1341 | ]
1342 | },
1343 | "execution_count": 28,
1344 | "metadata": {},
1345 | "output_type": "execute_result"
1346 | }
1347 | ],
1348 | "source": [
1349 | "countries"
1350 | ]
1351 | },
1352 | {
1353 | "cell_type": "code",
1354 | "execution_count": null,
1355 | "id": "895c41e1",
1356 | "metadata": {},
1357 | "outputs": [],
1358 | "source": []
1359 | },
1360 | {
1361 | "cell_type": "markdown",
1362 | "id": "43394e1a",
1363 | "metadata": {},
1364 | "source": [
1365 | "## Using Slicing\n",
1366 | "\n",
1367 | "- Slicing with **[::-1]** creates a reversed copy of the sequence without modifying the original sequence."
1368 | ]
1369 | },
1370 | {
1371 | "cell_type": "code",
1372 | "execution_count": 29,
1373 | "id": "cc4abc49",
1374 | "metadata": {},
1375 | "outputs": [
1376 | {
1377 | "data": {
1378 | "text/plain": [
1379 | "['Egypt', 'Spain', 'England', 'Qatar', 'Saudi Arabia', 'Jordan']"
1380 | ]
1381 | },
1382 | "execution_count": 29,
1383 | "metadata": {},
1384 | "output_type": "execute_result"
1385 | }
1386 | ],
1387 | "source": [
1388 | "countries = ['Jordan', 'Saudi Arabia', 'Qatar', 'England', 'Spain', 'Egypt']\n",
1389 | "countries[::-1]"
1390 | ]
1391 | },
1392 | {
1393 | "cell_type": "code",
1394 | "execution_count": null,
1395 | "id": "0bccf905",
1396 | "metadata": {},
1397 | "outputs": [],
1398 | "source": []
1399 | },
1400 | {
1401 | "cell_type": "code",
1402 | "execution_count": null,
1403 | "id": "c52cf95e",
1404 | "metadata": {},
1405 | "outputs": [],
1406 | "source": []
1407 | },
1408 | {
1409 | "cell_type": "code",
1410 | "execution_count": 30,
1411 | "id": "521d8e8f",
1412 | "metadata": {},
1413 | "outputs": [
1414 | {
1415 | "data": {
1416 | "text/plain": [
1417 | "['Jordan', 'Saudi Arabia', 'Qatar', 'England', 'Spain', 'Egypt']"
1418 | ]
1419 | },
1420 | "execution_count": 30,
1421 | "metadata": {},
1422 | "output_type": "execute_result"
1423 | }
1424 | ],
1425 | "source": [
1426 | "countries = ['Jordan', 'Saudi Arabia', 'Qatar', 'England', 'Spain', 'Egypt']\n",
1427 | "countries"
1428 | ]
1429 | },
1430 | {
1431 | "cell_type": "code",
1432 | "execution_count": null,
1433 | "id": "9670e1bc",
1434 | "metadata": {},
1435 | "outputs": [],
1436 | "source": []
1437 | },
1438 | {
1439 | "cell_type": "markdown",
1440 | "id": "0fa3906d",
1441 | "metadata": {},
1442 | "source": [
1443 | "## Using reversed()\n",
1444 | "- The reversed() function returns an iterator that yields elements of the sequence in reverse order. You need to convert it back to a list to see the reversed result.\n"
1445 | ]
1446 | },
1447 | {
1448 | "cell_type": "code",
1449 | "execution_count": 31,
1450 | "id": "7e2d3176",
1451 | "metadata": {},
1452 | "outputs": [
1453 | {
1454 | "name": "stdout",
1455 | "output_type": "stream",
1456 | "text": [
1457 | "Egypt\n",
1458 | "Spain\n",
1459 | "England\n",
1460 | "Qatar\n",
1461 | "Saudi Arabia\n",
1462 | "Jordan\n"
1463 | ]
1464 | }
1465 | ],
1466 | "source": [
1467 | "for country in reversed(countries):\n",
1468 | " print(country)"
1469 | ]
1470 | },
1471 | {
1472 | "cell_type": "code",
1473 | "execution_count": 32,
1474 | "id": "6fa74f9c",
1475 | "metadata": {},
1476 | "outputs": [
1477 | {
1478 | "data": {
1479 | "text/plain": [
1480 | "['Egypt', 'Spain', 'England', 'Qatar', 'Saudi Arabia', 'Jordan']"
1481 | ]
1482 | },
1483 | "execution_count": 32,
1484 | "metadata": {},
1485 | "output_type": "execute_result"
1486 | }
1487 | ],
1488 | "source": [
1489 | "reversed_countries = list(reversed(countries))\n",
1490 | "reversed_countries"
1491 | ]
1492 | },
1493 | {
1494 | "cell_type": "code",
1495 | "execution_count": null,
1496 | "id": "ed69f246",
1497 | "metadata": {},
1498 | "outputs": [],
1499 | "source": []
1500 | },
1501 | {
1502 | "cell_type": "markdown",
1503 | "id": "6e17d125",
1504 | "metadata": {},
1505 | "source": [
1506 | "## Incorrect Usages"
1507 | ]
1508 | },
1509 | {
1510 | "cell_type": "code",
1511 | "execution_count": 33,
1512 | "id": "50526c21",
1513 | "metadata": {},
1514 | "outputs": [
1515 | {
1516 | "ename": "AttributeError",
1517 | "evalue": "'str' object has no attribute 'reverse'",
1518 | "output_type": "error",
1519 | "traceback": [
1520 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
1521 | "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
1522 | "Cell \u001b[1;32mIn[33], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mEgypet\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;241m.\u001b[39mreverse()\n",
1523 | "\u001b[1;31mAttributeError\u001b[0m: 'str' object has no attribute 'reverse'"
1524 | ]
1525 | }
1526 | ],
1527 | "source": [
1528 | "'Egypet'.reverse()"
1529 | ]
1530 | },
1531 | {
1532 | "cell_type": "code",
1533 | "execution_count": 34,
1534 | "id": "fa7615c0",
1535 | "metadata": {},
1536 | "outputs": [
1537 | {
1538 | "ename": "AttributeError",
1539 | "evalue": "'tuple' object has no attribute 'reverse'",
1540 | "output_type": "error",
1541 | "traceback": [
1542 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
1543 | "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
1544 | "Cell \u001b[1;32mIn[34], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m countries \u001b[38;5;241m=\u001b[39m [\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mEgypt\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mSpain\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mEngland\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mQatar\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mSaudi Arabia\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mJordan\u001b[39m\u001b[38;5;124m'\u001b[39m]\n\u001b[1;32m----> 2\u001b[0m \u001b[38;5;28mtuple\u001b[39m(countries)\u001b[38;5;241m.\u001b[39mreverse()\n",
1545 | "\u001b[1;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'reverse'"
1546 | ]
1547 | }
1548 | ],
1549 | "source": [
1550 | "countries = ['Egypt', 'Spain', 'England', 'Qatar', 'Saudi Arabia', 'Jordan']\n",
1551 | "tuple(countries).reverse()"
1552 | ]
1553 | },
1554 | {
1555 | "cell_type": "code",
1556 | "execution_count": null,
1557 | "id": "09aaf5c8",
1558 | "metadata": {},
1559 | "outputs": [],
1560 | "source": []
1561 | },
1562 | {
1563 | "cell_type": "markdown",
1564 | "id": "1cc8cb2e",
1565 | "metadata": {},
1566 | "source": [
1567 | "## Reversing a string using slicing:"
1568 | ]
1569 | },
1570 | {
1571 | "cell_type": "code",
1572 | "execution_count": 35,
1573 | "id": "73326e4f",
1574 | "metadata": {},
1575 | "outputs": [
1576 | {
1577 | "data": {
1578 | "text/plain": [
1579 | "'tpygE'"
1580 | ]
1581 | },
1582 | "execution_count": 35,
1583 | "metadata": {},
1584 | "output_type": "execute_result"
1585 | }
1586 | ],
1587 | "source": [
1588 | "'Egypt'[::-1]"
1589 | ]
1590 | },
1591 | {
1592 | "cell_type": "code",
1593 | "execution_count": null,
1594 | "id": "dbbc49c8",
1595 | "metadata": {},
1596 | "outputs": [],
1597 | "source": []
1598 | },
1599 | {
1600 | "cell_type": "markdown",
1601 | "id": "2c9a3ac4",
1602 | "metadata": {},
1603 | "source": [
1604 | "## Reversing a tuple:"
1605 | ]
1606 | },
1607 | {
1608 | "cell_type": "code",
1609 | "execution_count": 36,
1610 | "id": "c0d1be3a",
1611 | "metadata": {},
1612 | "outputs": [
1613 | {
1614 | "name": "stdout",
1615 | "output_type": "stream",
1616 | "text": [
1617 | "Jordan\n",
1618 | "Saudi Arabia\n",
1619 | "Qatar\n",
1620 | "England\n",
1621 | "Spain\n",
1622 | "Egypt\n"
1623 | ]
1624 | }
1625 | ],
1626 | "source": [
1627 | "for country in reversed(tuple(countries)):\n",
1628 | " print(country)"
1629 | ]
1630 | },
1631 | {
1632 | "cell_type": "code",
1633 | "execution_count": null,
1634 | "id": "d6f613d7",
1635 | "metadata": {},
1636 | "outputs": [],
1637 | "source": []
1638 | },
1639 | {
1640 | "cell_type": "markdown",
1641 | "id": "316c062a",
1642 | "metadata": {},
1643 | "source": [
1644 | "# Sequence Reversal Methods in Python\n",
1645 | "\n",
1646 | "\n",
1647 | " \n",
1648 | " \n",
1649 | " | Method | \n",
1650 | " Description | \n",
1651 | " Example Code | \n",
1652 | " Considerations | \n",
1653 | "
\n",
1654 | " \n",
1655 | " \n",
1656 | " \n",
1657 | " | `reverse()` | \n",
1658 | " Reverses a mutable sequence in-place | \n",
1659 | " \n",
1660 | " numbers = [1, 2, 3, 4, 5]\n",
1661 | "numbers.reverse()\n",
1662 | "print(numbers) # Output: [5, 4, 3, 2, 1] \n",
1663 | " | \n",
1664 | " \n",
1665 | " - Not available for immutable sequences. - Modifies the list in place.\n",
1666 | " | \n",
1667 | "
\n",
1668 | " \n",
1669 | " | Slicing `[::-1]` | \n",
1670 | " Creates a reversed copy of a sequence | \n",
1671 | " \n",
1672 | " numbers = [1, 2, 3, 4, 5]\n",
1673 | "reversed_numbers = numbers[::-1]\n",
1674 | "print(reversed_numbers) # Output: [5, 4, 3, 2, 1] \n",
1675 | " | \n",
1676 | " \n",
1677 | " - Fastest for creating a reversed copy. - Creates a new list, which may be memory-intensive for large sequences.\n",
1678 | " | \n",
1679 | "
\n",
1680 | " \n",
1681 | " | `reversed()` | \n",
1682 | " Returns a reverse iterator | \n",
1683 | " \n",
1684 | " numbers = [1, 2, 3, 4, 5]\n",
1685 | "reversed_iterator = reversed(numbers)\n",
1686 | "print(list(reversed_iterator)) # Output: [5, 4, 3, 2, 1] \n",
1687 | " | \n",
1688 | " \n",
1689 | " - Efficient for large sequences. - Does not modify the original sequence.\n",
1690 | " | \n",
1691 | "
\n",
1692 | " \n",
1693 | "
\n"
1694 | ]
1695 | },
1696 | {
1697 | "cell_type": "code",
1698 | "execution_count": null,
1699 | "id": "c7b61f20",
1700 | "metadata": {},
1701 | "outputs": [],
1702 | "source": []
1703 | },
1704 | {
1705 | "cell_type": "code",
1706 | "execution_count": null,
1707 | "id": "cad5faef",
1708 | "metadata": {},
1709 | "outputs": [],
1710 | "source": []
1711 | },
1712 | {
1713 | "cell_type": "markdown",
1714 | "id": "c98e019f",
1715 | "metadata": {},
1716 | "source": [
1717 | "## Palindrome Challenge\n",
1718 | "A palindrome is a sequence that reads the same forward and backward, ignoring spaces, punctuation, and capitalization."
1719 | ]
1720 | },
1721 | {
1722 | "cell_type": "code",
1723 | "execution_count": 37,
1724 | "id": "a0005e75",
1725 | "metadata": {},
1726 | "outputs": [
1727 | {
1728 | "name": "stdout",
1729 | "output_type": "stream",
1730 | "text": [
1731 | "\"A man, a plan, a canal, Panama\" is a palindrome: True\n",
1732 | "\"No 'x' in Nixon\" is a palindrome: True\n",
1733 | "\"Hello, World!\" is a palindrome: False\n",
1734 | "\"Was it a car or a cat I saw?\" is a palindrome: True\n",
1735 | "\"Able was I ere I saw Elba\" is a palindrome: True\n"
1736 | ]
1737 | }
1738 | ],
1739 | "source": [
1740 | "import re\n",
1741 | "\n",
1742 | "def is_palindrome(s):\n",
1743 | " # Normalize the string: convert to lowercase and remove non-alphanumeric characters\n",
1744 | " normalized_str = re.sub(r'[^a-zA-Z0-9]', '', s).lower()\n",
1745 | " \n",
1746 | " # Check if the normalized string is equal to its reverse\n",
1747 | " return normalized_str == normalized_str[::-1]\n",
1748 | "\n",
1749 | "# Test cases\n",
1750 | "test_strings = [\n",
1751 | " \"A man, a plan, a canal, Panama\",\n",
1752 | " \"No 'x' in Nixon\",\n",
1753 | " \"Hello, World!\",\n",
1754 | " \"Was it a car or a cat I saw?\",\n",
1755 | " \"Able was I ere I saw Elba\"\n",
1756 | "]\n",
1757 | "\n",
1758 | "# Running the function on test cases\n",
1759 | "for test in test_strings:\n",
1760 | " result = is_palindrome(test)\n",
1761 | " print(f'\"{test}\" is a palindrome: {result}')\n"
1762 | ]
1763 | },
1764 | {
1765 | "cell_type": "code",
1766 | "execution_count": null,
1767 | "id": "a856a3b8",
1768 | "metadata": {},
1769 | "outputs": [],
1770 | "source": []
1771 | },
1772 | {
1773 | "cell_type": "code",
1774 | "execution_count": null,
1775 | "id": "449c3e50",
1776 | "metadata": {},
1777 | "outputs": [],
1778 | "source": [
1779 | "\n"
1780 | ]
1781 | },
1782 | {
1783 | "cell_type": "code",
1784 | "execution_count": 38,
1785 | "id": "bffef7fb",
1786 | "metadata": {},
1787 | "outputs": [],
1788 | "source": [
1789 | "words = 'Hello'"
1790 | ]
1791 | },
1792 | {
1793 | "cell_type": "code",
1794 | "execution_count": 39,
1795 | "id": "74d7724f",
1796 | "metadata": {},
1797 | "outputs": [
1798 | {
1799 | "data": {
1800 | "text/plain": [
1801 | ""
1802 | ]
1803 | },
1804 | "execution_count": 39,
1805 | "metadata": {},
1806 | "output_type": "execute_result"
1807 | }
1808 | ],
1809 | "source": [
1810 | "reversed(words)"
1811 | ]
1812 | },
1813 | {
1814 | "cell_type": "code",
1815 | "execution_count": 40,
1816 | "id": "e29500b4",
1817 | "metadata": {},
1818 | "outputs": [
1819 | {
1820 | "data": {
1821 | "text/plain": [
1822 | "'olleH'"
1823 | ]
1824 | },
1825 | "execution_count": 40,
1826 | "metadata": {},
1827 | "output_type": "execute_result"
1828 | }
1829 | ],
1830 | "source": [
1831 | "''.join(reversed(words))"
1832 | ]
1833 | },
1834 | {
1835 | "cell_type": "code",
1836 | "execution_count": null,
1837 | "id": "cc4b8079",
1838 | "metadata": {},
1839 | "outputs": [],
1840 | "source": []
1841 | },
1842 | {
1843 | "cell_type": "code",
1844 | "execution_count": 41,
1845 | "id": "05c5773e",
1846 | "metadata": {},
1847 | "outputs": [
1848 | {
1849 | "name": "stdout",
1850 | "output_type": "stream",
1851 | "text": [
1852 | "\"A man, a plan, a canal, Panama\" is a palindrome: True\n",
1853 | "\"No 'x' in Nixon\" is a palindrome: True\n",
1854 | "\"Hello, World!\" is a palindrome: False\n",
1855 | "\"Was it a car or a cat I saw?\" is a palindrome: True\n",
1856 | "\"Able was I ere I saw Elba\" is a palindrome: True\n"
1857 | ]
1858 | }
1859 | ],
1860 | "source": [
1861 | "def is_palindrome(s):\n",
1862 | "\n",
1863 | " normalized_str = re.sub(r'[^a-zA-Z0-9]', '', s).lower()\n",
1864 | " \n",
1865 | " # Reverse the normalized string using ''.join(reversed())\n",
1866 | " reversed_str = ''.join(reversed(normalized_str))\n",
1867 | " \n",
1868 | " # Check if the normalized string is equal to its reverse\n",
1869 | " return normalized_str == reversed_str\n",
1870 | "\n",
1871 | "for test in test_strings:\n",
1872 | " result = is_palindrome(test)\n",
1873 | " print(f'\"{test}\" is a palindrome: {result}')"
1874 | ]
1875 | },
1876 | {
1877 | "cell_type": "code",
1878 | "execution_count": null,
1879 | "id": "bcce99ca",
1880 | "metadata": {},
1881 | "outputs": [],
1882 | "source": []
1883 | },
1884 | {
1885 | "cell_type": "code",
1886 | "execution_count": null,
1887 | "id": "93f63aba",
1888 | "metadata": {},
1889 | "outputs": [],
1890 | "source": []
1891 | },
1892 | {
1893 | "cell_type": "code",
1894 | "execution_count": null,
1895 | "id": "29b221c7",
1896 | "metadata": {},
1897 | "outputs": [],
1898 | "source": []
1899 | },
1900 | {
1901 | "cell_type": "markdown",
1902 | "id": "30f3cf07",
1903 | "metadata": {},
1904 | "source": [
1905 | "---"
1906 | ]
1907 | },
1908 | {
1909 | "cell_type": "markdown",
1910 | "id": "68649b69",
1911 | "metadata": {},
1912 | "source": [
1913 | "# In-Depth Examples of min() and max()\n",
1914 | "\n",
1915 | "The min() and max() functions in Python are used to find the smallest and largest values in an iterable or among multiple arguments. "
1916 | ]
1917 | },
1918 | {
1919 | "cell_type": "code",
1920 | "execution_count": 42,
1921 | "id": "9486316a",
1922 | "metadata": {},
1923 | "outputs": [
1924 | {
1925 | "data": {
1926 | "text/plain": [
1927 | "30"
1928 | ]
1929 | },
1930 | "execution_count": 42,
1931 | "metadata": {},
1932 | "output_type": "execute_result"
1933 | }
1934 | ],
1935 | "source": [
1936 | "max(10,22,30)"
1937 | ]
1938 | },
1939 | {
1940 | "cell_type": "markdown",
1941 | "id": "d630b886",
1942 | "metadata": {},
1943 | "source": [
1944 | "## Finding the Maximum Value"
1945 | ]
1946 | },
1947 | {
1948 | "cell_type": "code",
1949 | "execution_count": 43,
1950 | "id": "54e899a2",
1951 | "metadata": {},
1952 | "outputs": [
1953 | {
1954 | "name": "stdout",
1955 | "output_type": "stream",
1956 | "text": [
1957 | "30\n"
1958 | ]
1959 | }
1960 | ],
1961 | "source": [
1962 | "numbers = [10, 22, 30]\n",
1963 | "print(max(numbers)) "
1964 | ]
1965 | },
1966 | {
1967 | "cell_type": "code",
1968 | "execution_count": null,
1969 | "id": "aeb38438",
1970 | "metadata": {},
1971 | "outputs": [],
1972 | "source": []
1973 | },
1974 | {
1975 | "cell_type": "code",
1976 | "execution_count": 44,
1977 | "id": "5ecbfd5d",
1978 | "metadata": {},
1979 | "outputs": [],
1980 | "source": [
1981 | "countries = ['France', 'India', 'Mexico', 'South Korea', 'Turkey', 'Italy']\n",
1982 | "populations = [10_000_000, 20_000_000, 30_000_000, 40_000_000, 50_000_000, 60_000_000]"
1983 | ]
1984 | },
1985 | {
1986 | "cell_type": "markdown",
1987 | "id": "15d27b4f",
1988 | "metadata": {},
1989 | "source": [
1990 | "## Finding the Maximum Population"
1991 | ]
1992 | },
1993 | {
1994 | "cell_type": "code",
1995 | "execution_count": 45,
1996 | "id": "5b6c7653",
1997 | "metadata": {},
1998 | "outputs": [
1999 | {
2000 | "data": {
2001 | "text/plain": [
2002 | "60000000"
2003 | ]
2004 | },
2005 | "execution_count": 45,
2006 | "metadata": {},
2007 | "output_type": "execute_result"
2008 | }
2009 | ],
2010 | "source": [
2011 | "max(populations)"
2012 | ]
2013 | },
2014 | {
2015 | "cell_type": "code",
2016 | "execution_count": null,
2017 | "id": "3b0db608",
2018 | "metadata": {},
2019 | "outputs": [],
2020 | "source": []
2021 | },
2022 | {
2023 | "cell_type": "markdown",
2024 | "id": "abe86f8c",
2025 | "metadata": {},
2026 | "source": [
2027 | "## Using min() and max() with Pairs\n",
2028 | "We can use zip() to pair countries with their populations and then use min() and max() to find the country with the smallest or largest population."
2029 | ]
2030 | },
2031 | {
2032 | "cell_type": "code",
2033 | "execution_count": 46,
2034 | "id": "1678231e",
2035 | "metadata": {},
2036 | "outputs": [
2037 | {
2038 | "name": "stdout",
2039 | "output_type": "stream",
2040 | "text": [
2041 | "[('France', 10000000), ('India', 20000000), ('Mexico', 30000000), ('South Korea', 40000000), ('Turkey', 50000000), ('Italy', 60000000)]\n"
2042 | ]
2043 | }
2044 | ],
2045 | "source": [
2046 | "countries = ['France', 'India', 'Mexico', 'South Korea', 'Turkey', 'Italy']\n",
2047 | "populations = [10_000_000, 20_000_000, 30_000_000, 40_000_000, 50_000_000, 60_000_000]\n",
2048 | "\n",
2049 | "pairs = list(zip(countries, populations))\n",
2050 | "print(pairs)"
2051 | ]
2052 | },
2053 | {
2054 | "cell_type": "code",
2055 | "execution_count": null,
2056 | "id": "7bfac41b",
2057 | "metadata": {},
2058 | "outputs": [],
2059 | "source": []
2060 | },
2061 | {
2062 | "cell_type": "markdown",
2063 | "id": "832f174f",
2064 | "metadata": {},
2065 | "source": [
2066 | "### Finding the Country with the Minimum Population\n"
2067 | ]
2068 | },
2069 | {
2070 | "cell_type": "code",
2071 | "execution_count": 47,
2072 | "id": "a365fd36",
2073 | "metadata": {},
2074 | "outputs": [
2075 | {
2076 | "name": "stdout",
2077 | "output_type": "stream",
2078 | "text": [
2079 | "('France', 10000000)\n"
2080 | ]
2081 | }
2082 | ],
2083 | "source": [
2084 | "print(min(pairs))"
2085 | ]
2086 | },
2087 | {
2088 | "cell_type": "code",
2089 | "execution_count": null,
2090 | "id": "fa6cfc7b",
2091 | "metadata": {},
2092 | "outputs": [],
2093 | "source": []
2094 | },
2095 | {
2096 | "cell_type": "markdown",
2097 | "id": "10a02e90",
2098 | "metadata": {},
2099 | "source": [
2100 | "## Using a key function:"
2101 | ]
2102 | },
2103 | {
2104 | "cell_type": "code",
2105 | "execution_count": 48,
2106 | "id": "3a1727f5",
2107 | "metadata": {},
2108 | "outputs": [
2109 | {
2110 | "name": "stdout",
2111 | "output_type": "stream",
2112 | "text": [
2113 | "('France', 10000000)\n"
2114 | ]
2115 | }
2116 | ],
2117 | "source": [
2118 | "def get_population(pair):\n",
2119 | " country, population = pair\n",
2120 | " return population\n",
2121 | "\n",
2122 | "print(min(pairs, key=get_population))"
2123 | ]
2124 | },
2125 | {
2126 | "cell_type": "markdown",
2127 | "id": "d736bbf9",
2128 | "metadata": {},
2129 | "source": [
2130 | "## Using a lambda function:"
2131 | ]
2132 | },
2133 | {
2134 | "cell_type": "code",
2135 | "execution_count": 49,
2136 | "id": "14be4b5c",
2137 | "metadata": {},
2138 | "outputs": [
2139 | {
2140 | "name": "stdout",
2141 | "output_type": "stream",
2142 | "text": [
2143 | "('France', 10000000)\n"
2144 | ]
2145 | }
2146 | ],
2147 | "source": [
2148 | "print(min(pairs, key=lambda x: x[1]))"
2149 | ]
2150 | },
2151 | {
2152 | "cell_type": "markdown",
2153 | "id": "150016a7",
2154 | "metadata": {},
2155 | "source": [
2156 | "## Using max() directly:\n"
2157 | ]
2158 | },
2159 | {
2160 | "cell_type": "code",
2161 | "execution_count": 50,
2162 | "id": "6f0bb335",
2163 | "metadata": {},
2164 | "outputs": [
2165 | {
2166 | "name": "stdout",
2167 | "output_type": "stream",
2168 | "text": [
2169 | "('Turkey', 50000000)\n"
2170 | ]
2171 | }
2172 | ],
2173 | "source": [
2174 | "print(max(pairs))"
2175 | ]
2176 | },
2177 | {
2178 | "cell_type": "code",
2179 | "execution_count": null,
2180 | "id": "45e1374c",
2181 | "metadata": {},
2182 | "outputs": [],
2183 | "source": []
2184 | },
2185 | {
2186 | "cell_type": "markdown",
2187 | "id": "eb281145",
2188 | "metadata": {},
2189 | "source": [
2190 | "## Using a key function:"
2191 | ]
2192 | },
2193 | {
2194 | "cell_type": "code",
2195 | "execution_count": 51,
2196 | "id": "92b24aca",
2197 | "metadata": {},
2198 | "outputs": [
2199 | {
2200 | "name": "stdout",
2201 | "output_type": "stream",
2202 | "text": [
2203 | "('Italy', 60000000)\n"
2204 | ]
2205 | }
2206 | ],
2207 | "source": [
2208 | "print(max(pairs, key=get_population))"
2209 | ]
2210 | },
2211 | {
2212 | "cell_type": "code",
2213 | "execution_count": null,
2214 | "id": "1cb2c594",
2215 | "metadata": {},
2216 | "outputs": [],
2217 | "source": []
2218 | },
2219 | {
2220 | "cell_type": "markdown",
2221 | "id": "2cb4315a",
2222 | "metadata": {},
2223 | "source": [
2224 | "## Using min() and max() with Tuples"
2225 | ]
2226 | },
2227 | {
2228 | "cell_type": "code",
2229 | "execution_count": 52,
2230 | "id": "5281909d",
2231 | "metadata": {},
2232 | "outputs": [
2233 | {
2234 | "name": "stdout",
2235 | "output_type": "stream",
2236 | "text": [
2237 | "(10000000, 'France')\n"
2238 | ]
2239 | }
2240 | ],
2241 | "source": [
2242 | "print(min(zip(populations, countries)))"
2243 | ]
2244 | },
2245 | {
2246 | "cell_type": "code",
2247 | "execution_count": null,
2248 | "id": "7955cce1",
2249 | "metadata": {},
2250 | "outputs": [],
2251 | "source": []
2252 | },
2253 | {
2254 | "cell_type": "markdown",
2255 | "id": "3160a20f",
2256 | "metadata": {},
2257 | "source": [
2258 | "## Maximum by Population First"
2259 | ]
2260 | },
2261 | {
2262 | "cell_type": "code",
2263 | "execution_count": 53,
2264 | "id": "b570f8ad",
2265 | "metadata": {},
2266 | "outputs": [
2267 | {
2268 | "name": "stdout",
2269 | "output_type": "stream",
2270 | "text": [
2271 | "(60000000, 'Italy')\n"
2272 | ]
2273 | }
2274 | ],
2275 | "source": [
2276 | "print(max(zip(populations, countries)))"
2277 | ]
2278 | },
2279 | {
2280 | "cell_type": "code",
2281 | "execution_count": null,
2282 | "id": "6faa6d17",
2283 | "metadata": {},
2284 | "outputs": [],
2285 | "source": []
2286 | },
2287 | {
2288 | "cell_type": "code",
2289 | "execution_count": 54,
2290 | "id": "12889360",
2291 | "metadata": {},
2292 | "outputs": [
2293 | {
2294 | "name": "stdout",
2295 | "output_type": "stream",
2296 | "text": [
2297 | "The country with the smallest population is France with 10000000 people.\n",
2298 | "The country with the largest population is Italy with 60000000 people.\n"
2299 | ]
2300 | }
2301 | ],
2302 | "source": [
2303 | "countries = ['France', 'India', 'Mexico', 'South Korea', 'Turkey', 'Italy']\n",
2304 | "populations = [10_000_000, 20_000_000, 30_000_000, 40_000_000, 50_000_000, 60_000_000]\n",
2305 | "\n",
2306 | "pairs = list(zip(countries, populations))\n",
2307 | "\n",
2308 | "min_population_country = min(pairs, key=lambda x: x[1])\n",
2309 | "max_population_country = max(pairs, key=lambda x: x[1])\n",
2310 | "\n",
2311 | "print(f'The country with the smallest population is {min_population_country[0]} with {min_population_country[1]} people.')\n",
2312 | "print(f'The country with the largest population is {max_population_country[0]} with {max_population_country[1]} people.')\n"
2313 | ]
2314 | },
2315 | {
2316 | "cell_type": "code",
2317 | "execution_count": null,
2318 | "id": "8a71a248",
2319 | "metadata": {},
2320 | "outputs": [],
2321 | "source": []
2322 | },
2323 | {
2324 | "cell_type": "markdown",
2325 | "id": "4a323e11",
2326 | "metadata": {},
2327 | "source": [
2328 | "## Summary Table for `min()` and `max()`\n",
2329 | "\n",
2330 | "| Function | Example | Output | Explanation |\n",
2331 | "| --- | --- | --- | --- |\n",
2332 | "| `max(numbers)` | `max([10, 22, 30])` | `30` | Finds the maximum value in the list of numbers. |\n",
2333 | "| `max(populations)` | `max([10_000_000, 20_000_000, 30_000_000, 40_000_000, 50_000_000, 60_000_000])` | `60,000,000` | Finds the maximum population in the list. |\n",
2334 | "| `min(pairs)` | `min([('France', 10_000_000), ('India', 20_000_000), ('Mexico', 30_000_000), ('South Korea', 40_000_000), ('Turkey', 50_000_000), ('Italy', 60_000_000)])` | `('France', 10_000_000)` | Finds the minimum tuple based on the first element (country name). |\n",
2335 | "| `max(pairs)` | `max([('France', 10_000_000), ('India', 20_000_000), ('Mexico', 30_000_000), ('South Korea', 40_000_000), ('Turkey', 50_000_000), ('Italy', 60_000_000)])` | `('Turkey', 50_000_000)` | Finds the maximum tuple based on the first element (country name). |\n",
2336 | "| `min(pairs, key=get_population)` | `min(pairs, key=lambda x: x[1])` | `('France', 10_000_000)` | Finds the minimum tuple based on the second element (population). |\n",
2337 | "| `max(pairs, key=get_population)` | `max(pairs, key=lambda x: x[1])` | `('Italy', 60_000_000)` | Finds the maximum tuple based on the second element (population). |\n",
2338 | "| `min(zip(populations, countries))` | `min(zip([10_000_000, 20_000_000, 30_000_000, 40_000_000, 50_000_000, 60_000_000], ['France', 'India', 'Mexico', 'South Korea', 'Turkey', 'Italy']))` | `(10_000_000, 'France')` | Finds the minimum pair based on the population. |\n",
2339 | "| `max(zip(populations, countries))` | `max(zip([10_000_000, 20_000_000, 30_000_000, 40_000_000, 50_000_000, 60_000_000], ['France', 'India', 'Mexico', 'South Korea', 'Turkey', 'Italy']))` | `(60_000_000, 'Italy')` | Finds the maximum pair based on the population. |\n",
2340 | "\n",
2341 | "**Explanation:**\n",
2342 | "\n",
2343 | "- The `max()` and `min()` functions are used to find the maximum and minimum values, respectively, in a list or iterable.\n",
2344 | "- When used with `zip()`, they operate on pairs of values.\n",
2345 | "- Using a `key` argument allows specifying a function to extract a value for comparison, which can be useful when working with tuples or other complex data structures.\n"
2346 | ]
2347 | },
2348 | {
2349 | "cell_type": "markdown",
2350 | "id": "dc1c7da3",
2351 | "metadata": {},
2352 | "source": [
2353 | "____"
2354 | ]
2355 | },
2356 | {
2357 | "cell_type": "markdown",
2358 | "id": "7129415f",
2359 | "metadata": {},
2360 | "source": [
2361 | "# Challenge max() and min()\n",
2362 | "\n",
2363 | "- You are given a list of valid Scrabble words from a file and a sentence. Your task is to calculate the Scrabble score for each word in the sentence based on predefined letter values and determine the word with the highest score and the word with the lowest score."
2364 | ]
2365 | },
2366 | {
2367 | "cell_type": "code",
2368 | "execution_count": null,
2369 | "id": "3129dd45",
2370 | "metadata": {},
2371 | "outputs": [],
2372 | "source": []
2373 | },
2374 | {
2375 | "cell_type": "code",
2376 | "execution_count": 55,
2377 | "id": "6e7c9d08",
2378 | "metadata": {},
2379 | "outputs": [
2380 | {
2381 | "data": {
2382 | "text/plain": [
2383 | "'C:\\\\Users\\\\elhas\\\\OneDrive\\\\Desktop\\\\8-Essential-Python-Tips-Every-Developer-Should-Know\\\\dictionary.txt'"
2384 | ]
2385 | },
2386 | "execution_count": 55,
2387 | "metadata": {},
2388 | "output_type": "execute_result"
2389 | }
2390 | ],
2391 | "source": [
2392 | "# Let's create a sample dictionary.txt file with some Scrabble words.\n",
2393 | "dictionary_words = [\n",
2394 | " \"example\", \"scrabble\", \"word\", \"python\", \"dictionary\", \"valid\", \"letters\", \"score\",\n",
2395 | " \"game\", \"play\", \"board\", \"tiles\", \"triple\", \"double\", \"bonus\", \"challenge\" , \"ELHASSAN\" , \"8_Essential_Python_Tips\" ,\n",
2396 | " \"palestinewillbefree\"\n",
2397 | "]\n",
2398 | "\n",
2399 | "# Writing the words to a file named dictionary.txt\n",
2400 | "file_path = r'C:\\Users\\elhas\\OneDrive\\Desktop\\8-Essential-Python-Tips-Every-Developer-Should-Know\\dictionary.txt'\n",
2401 | "with open(file_path, 'w', encoding='utf-8') as file:\n",
2402 | " for word in dictionary_words:\n",
2403 | " file.write(word + '\\n')\n",
2404 | "\n",
2405 | "file_path"
2406 | ]
2407 | },
2408 | {
2409 | "cell_type": "code",
2410 | "execution_count": null,
2411 | "id": "ac1bef53",
2412 | "metadata": {},
2413 | "outputs": [],
2414 | "source": []
2415 | },
2416 | {
2417 | "cell_type": "code",
2418 | "execution_count": 56,
2419 | "id": "8bd9e4b9",
2420 | "metadata": {},
2421 | "outputs": [],
2422 | "source": [
2423 | "#with open('/mnt/data/dictionary.txt', 'w', encoding='utf-8') as file:\n",
2424 | "# file.write('\\n'.join(words))"
2425 | ]
2426 | },
2427 | {
2428 | "cell_type": "code",
2429 | "execution_count": null,
2430 | "id": "0c804f7a",
2431 | "metadata": {},
2432 | "outputs": [],
2433 | "source": []
2434 | },
2435 | {
2436 | "cell_type": "code",
2437 | "execution_count": 57,
2438 | "id": "b2222c4a",
2439 | "metadata": {},
2440 | "outputs": [],
2441 | "source": [
2442 | "import string\n",
2443 | "\n",
2444 | "# Define the dictionary file and letter scores\n",
2445 | "DICTIONARY = 'dictionary.txt'\n",
2446 | "letter_scores = {\n",
2447 | " 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4,\n",
2448 | " 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3,\n",
2449 | " 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8,\n",
2450 | " 'y': 4, 'z': 10\n",
2451 | "}\n",
2452 | "\n",
2453 | "def get_scrabble_dictionary():\n",
2454 | " \"\"\"Helper function to return the words in DICTIONARY as a list.\"\"\"\n",
2455 | " with open(DICTIONARY, 'r', encoding='utf-8') as file:\n",
2456 | " content = file.read().splitlines()\n",
2457 | " return content\n",
2458 | "\n",
2459 | "def score_word(word):\n",
2460 | " \"\"\"Return the score for a word using letter_scores.\n",
2461 | " If the word isn't in DICTIONARY, it gets a score of 0.\"\"\"\n",
2462 | " scrabble_dictionary = set(get_scrabble_dictionary())\n",
2463 | " cleaned_word = remove_punctuation(word).lower()\n",
2464 | " if cleaned_word not in scrabble_dictionary:\n",
2465 | " return 0\n",
2466 | " score = sum(letter_scores.get(letter, 0) for letter in cleaned_word)\n",
2467 | " return score\n",
2468 | "\n",
2469 | "def remove_punctuation(word):\n",
2470 | " \"\"\"Helper function to remove punctuation from a word.\"\"\"\n",
2471 | " table = str.maketrans('', '', string.punctuation)\n",
2472 | " return word.translate(table)\n",
2473 | "\n",
2474 | "def get_word_largest_score(sentence):\n",
2475 | " \"\"\"Given a sentence, return the word in the sentence with the largest score.\"\"\"\n",
2476 | " words = sentence.split()\n",
2477 | " word_scores = {word: score_word(word) for word in words}\n",
2478 | " highest_score_word = max(word_scores, key=word_scores.get)\n",
2479 | " return highest_score_word, word_scores[highest_score_word]"
2480 | ]
2481 | },
2482 | {
2483 | "cell_type": "code",
2484 | "execution_count": 58,
2485 | "id": "9867ed14",
2486 | "metadata": {},
2487 | "outputs": [
2488 | {
2489 | "name": "stdout",
2490 | "output_type": "stream",
2491 | "text": [
2492 | "The score for the word \"python\" is 14.\n",
2493 | "The word with the highest score in the sentence is \"palestinewillbefree\" with a score of 29.\n"
2494 | ]
2495 | }
2496 | ],
2497 | "source": [
2498 | "# Example usage\n",
2499 | "word = \"python\"\n",
2500 | "score = score_word(word)\n",
2501 | "print(f'The score for the word \"{word}\" is {score}.')\n",
2502 | "\n",
2503 | "sentence = \"palestinewillbefree\"\n",
2504 | "word, score = get_word_largest_score(sentence)\n",
2505 | "print(f'The word with the highest score in the sentence is \"{word}\" with a score of {score}.')"
2506 | ]
2507 | },
2508 | {
2509 | "cell_type": "code",
2510 | "execution_count": null,
2511 | "id": "2bef6951",
2512 | "metadata": {},
2513 | "outputs": [],
2514 | "source": []
2515 | },
2516 | {
2517 | "cell_type": "code",
2518 | "execution_count": null,
2519 | "id": "0790028e",
2520 | "metadata": {},
2521 | "outputs": [],
2522 | "source": []
2523 | },
2524 | {
2525 | "cell_type": "code",
2526 | "execution_count": null,
2527 | "id": "c3ad1bc4",
2528 | "metadata": {},
2529 | "outputs": [],
2530 | "source": []
2531 | },
2532 | {
2533 | "cell_type": "markdown",
2534 | "id": "18caf95f",
2535 | "metadata": {},
2536 | "source": [
2537 | "---"
2538 | ]
2539 | },
2540 | {
2541 | "cell_type": "markdown",
2542 | "id": "87b9f0c8",
2543 | "metadata": {},
2544 | "source": [
2545 | "## In-Depth Examples of Sorted()\n",
2546 | "\n",
2547 | "- sorted(iterable, *, key=None, reverse=False)\n",
2548 | "\n",
2549 | "The sorted() function in Python offers a versatile approach to sorting elements within iterables (like lists, tuples, and strings). It creates a new sorted list, preserving the original one.\n",
2550 | "\n",
2551 | "- **iterable**: The data structure you want to sort (e.g., a list of countries, a string).\n",
2552 | "- **key** (optional): A function that defines the sorting criteria. It takes one element as input and returns a value used for comparison.\n",
2553 | "- **reverse** (optional): A boolean flag to sort in descending order (default is False for ascending)."
2554 | ]
2555 | },
2556 | {
2557 | "cell_type": "code",
2558 | "execution_count": 59,
2559 | "id": "150e88eb",
2560 | "metadata": {},
2561 | "outputs": [],
2562 | "source": [
2563 | "class Country:\n",
2564 | " def __init__(self,name,population):\n",
2565 | " self.name = name\n",
2566 | " self.population = population\n",
2567 | " def __repr__(self):\n",
2568 | " return f'Country({self.name},{self.population})'\n",
2569 | "\n",
2570 | "\n",
2571 | "country_list = [\n",
2572 | " Country('Egypt', 110_000_000),\n",
2573 | " Country('Saudi Arabia', 34_000_000),\n",
2574 | " Country('United Arab Emirates', 9_800_000),\n",
2575 | " Country('Algeria', 43_000_000),\n",
2576 | " Country('Morocco', 36_000_000),\n",
2577 | " Country('Iraq', 40_000_000),\n",
2578 | " Country('Sudan', 43_000_000),\n",
2579 | " Country('Syria', 17_500_000),\n",
2580 | " Country('Jordan', 10_000_000),\n",
2581 | " Country('Palestine', 5_000_000)\n",
2582 | "]\n"
2583 | ]
2584 | },
2585 | {
2586 | "cell_type": "code",
2587 | "execution_count": null,
2588 | "id": "8c21788b",
2589 | "metadata": {},
2590 | "outputs": [],
2591 | "source": []
2592 | },
2593 | {
2594 | "cell_type": "markdown",
2595 | "id": "6bcb6100",
2596 | "metadata": {},
2597 | "source": [
2598 | "## Ascending Order by Population\n"
2599 | ]
2600 | },
2601 | {
2602 | "cell_type": "code",
2603 | "execution_count": 60,
2604 | "id": "18ea5f6b",
2605 | "metadata": {},
2606 | "outputs": [
2607 | {
2608 | "data": {
2609 | "text/plain": [
2610 | "[Country(Palestine,5000000),\n",
2611 | " Country(United Arab Emirates,9800000),\n",
2612 | " Country(Jordan,10000000),\n",
2613 | " Country(Syria,17500000),\n",
2614 | " Country(Saudi Arabia,34000000),\n",
2615 | " Country(Morocco,36000000),\n",
2616 | " Country(Iraq,40000000),\n",
2617 | " Country(Algeria,43000000),\n",
2618 | " Country(Sudan,43000000),\n",
2619 | " Country(Egypt,110000000)]"
2620 | ]
2621 | },
2622 | "execution_count": 60,
2623 | "metadata": {},
2624 | "output_type": "execute_result"
2625 | }
2626 | ],
2627 | "source": [
2628 | "sorted(country_list,key=lambda x: x.population)"
2629 | ]
2630 | },
2631 | {
2632 | "cell_type": "code",
2633 | "execution_count": null,
2634 | "id": "d0699677",
2635 | "metadata": {},
2636 | "outputs": [],
2637 | "source": []
2638 | },
2639 | {
2640 | "cell_type": "markdown",
2641 | "id": "003ad44a",
2642 | "metadata": {},
2643 | "source": [
2644 | "## Descending Order by Population"
2645 | ]
2646 | },
2647 | {
2648 | "cell_type": "code",
2649 | "execution_count": 61,
2650 | "id": "54581c4a",
2651 | "metadata": {},
2652 | "outputs": [
2653 | {
2654 | "data": {
2655 | "text/plain": [
2656 | "[Country(Egypt,110000000),\n",
2657 | " Country(Algeria,43000000),\n",
2658 | " Country(Sudan,43000000),\n",
2659 | " Country(Iraq,40000000),\n",
2660 | " Country(Morocco,36000000),\n",
2661 | " Country(Saudi Arabia,34000000),\n",
2662 | " Country(Syria,17500000),\n",
2663 | " Country(Jordan,10000000),\n",
2664 | " Country(United Arab Emirates,9800000),\n",
2665 | " Country(Palestine,5000000)]"
2666 | ]
2667 | },
2668 | "execution_count": 61,
2669 | "metadata": {},
2670 | "output_type": "execute_result"
2671 | }
2672 | ],
2673 | "source": [
2674 | "sorted(country_list,key=lambda x: x.population, reverse=True)"
2675 | ]
2676 | },
2677 | {
2678 | "cell_type": "code",
2679 | "execution_count": null,
2680 | "id": "4069ee1b",
2681 | "metadata": {},
2682 | "outputs": [],
2683 | "source": []
2684 | },
2685 | {
2686 | "cell_type": "markdown",
2687 | "id": "dc1c7bfa",
2688 | "metadata": {},
2689 | "source": [
2690 | "## Sorting by Population (Descending Order)"
2691 | ]
2692 | },
2693 | {
2694 | "cell_type": "code",
2695 | "execution_count": 62,
2696 | "id": "fae26fae",
2697 | "metadata": {},
2698 | "outputs": [
2699 | {
2700 | "data": {
2701 | "text/plain": [
2702 | "[Country(Egypt,110000000),\n",
2703 | " Country(Algeria,43000000),\n",
2704 | " Country(Sudan,43000000),\n",
2705 | " Country(Iraq,40000000),\n",
2706 | " Country(Morocco,36000000),\n",
2707 | " Country(Saudi Arabia,34000000),\n",
2708 | " Country(Syria,17500000),\n",
2709 | " Country(Jordan,10000000),\n",
2710 | " Country(United Arab Emirates,9800000),\n",
2711 | " Country(Palestine,5000000)]"
2712 | ]
2713 | },
2714 | "execution_count": 62,
2715 | "metadata": {},
2716 | "output_type": "execute_result"
2717 | }
2718 | ],
2719 | "source": [
2720 | "sorted(country_list,key=lambda x: -x.population)"
2721 | ]
2722 | },
2723 | {
2724 | "cell_type": "code",
2725 | "execution_count": null,
2726 | "id": "1665665a",
2727 | "metadata": {},
2728 | "outputs": [],
2729 | "source": []
2730 | },
2731 | {
2732 | "cell_type": "markdown",
2733 | "id": "6dfc7f6c",
2734 | "metadata": {},
2735 | "source": [
2736 | "## Sorting by Population (Primary) and Name (Secondary):"
2737 | ]
2738 | },
2739 | {
2740 | "cell_type": "code",
2741 | "execution_count": 63,
2742 | "id": "21c3e346",
2743 | "metadata": {},
2744 | "outputs": [
2745 | {
2746 | "data": {
2747 | "text/plain": [
2748 | "[Country(Egypt,110000000),\n",
2749 | " Country(Algeria,43000000),\n",
2750 | " Country(Sudan,43000000),\n",
2751 | " Country(Iraq,40000000),\n",
2752 | " Country(Morocco,36000000),\n",
2753 | " Country(Saudi Arabia,34000000),\n",
2754 | " Country(Syria,17500000),\n",
2755 | " Country(Jordan,10000000),\n",
2756 | " Country(United Arab Emirates,9800000),\n",
2757 | " Country(Palestine,5000000)]"
2758 | ]
2759 | },
2760 | "execution_count": 63,
2761 | "metadata": {},
2762 | "output_type": "execute_result"
2763 | }
2764 | ],
2765 | "source": [
2766 | "sorted(country_list,key=lambda x: (-x.population,x.name))"
2767 | ]
2768 | },
2769 | {
2770 | "cell_type": "code",
2771 | "execution_count": null,
2772 | "id": "d3c56c12",
2773 | "metadata": {},
2774 | "outputs": [],
2775 | "source": []
2776 | },
2777 | {
2778 | "cell_type": "markdown",
2779 | "id": "580e1a55",
2780 | "metadata": {},
2781 | "source": [
2782 | "## Handling Unsupported Operations (Error Case):"
2783 | ]
2784 | },
2785 | {
2786 | "cell_type": "code",
2787 | "execution_count": 64,
2788 | "id": "206f3113",
2789 | "metadata": {},
2790 | "outputs": [
2791 | {
2792 | "name": "stdout",
2793 | "output_type": "stream",
2794 | "text": [
2795 | "Error: bad operand type for unary -: 'str'\n"
2796 | ]
2797 | }
2798 | ],
2799 | "source": [
2800 | "try:\n",
2801 | " sorted_by_invalid = sorted(country_list, key=lambda x: (-x.population, -x.name))\n",
2802 | "except TypeError as e:\n",
2803 | " print(f\"Error: {e}\")"
2804 | ]
2805 | },
2806 | {
2807 | "cell_type": "code",
2808 | "execution_count": null,
2809 | "id": "df24ea08",
2810 | "metadata": {},
2811 | "outputs": [],
2812 | "source": []
2813 | },
2814 | {
2815 | "cell_type": "markdown",
2816 | "id": "17e67dde",
2817 | "metadata": {},
2818 | "source": [
2819 | "## Sorting by Population (Descending Order) and Country Name (Ascending Order)"
2820 | ]
2821 | },
2822 | {
2823 | "cell_type": "code",
2824 | "execution_count": 65,
2825 | "id": "18c25268",
2826 | "metadata": {},
2827 | "outputs": [
2828 | {
2829 | "data": {
2830 | "text/plain": [
2831 | "[Country(Egypt,110000000),\n",
2832 | " Country(Sudan,43000000),\n",
2833 | " Country(Algeria,43000000),\n",
2834 | " Country(Iraq,40000000),\n",
2835 | " Country(Morocco,36000000),\n",
2836 | " Country(Saudi Arabia,34000000),\n",
2837 | " Country(Syria,17500000),\n",
2838 | " Country(Jordan,10000000),\n",
2839 | " Country(United Arab Emirates,9800000),\n",
2840 | " Country(Palestine,5000000)]"
2841 | ]
2842 | },
2843 | "execution_count": 65,
2844 | "metadata": {},
2845 | "output_type": "execute_result"
2846 | }
2847 | ],
2848 | "source": [
2849 | "sorted(country_list,key=lambda x: (x.population,x.name),reverse=True)"
2850 | ]
2851 | },
2852 | {
2853 | "cell_type": "code",
2854 | "execution_count": null,
2855 | "id": "474ff5ac",
2856 | "metadata": {},
2857 | "outputs": [],
2858 | "source": []
2859 | },
2860 | {
2861 | "cell_type": "markdown",
2862 | "id": "cbf4a6bc",
2863 | "metadata": {},
2864 | "source": [
2865 | "## Sorting a List of Country-ISO Pairs by Population"
2866 | ]
2867 | },
2868 | {
2869 | "cell_type": "code",
2870 | "execution_count": 66,
2871 | "id": "8d9b8a85",
2872 | "metadata": {},
2873 | "outputs": [],
2874 | "source": [
2875 | "iso = [\n",
2876 | " ('Egypt', 'iso110000000'),\n",
2877 | " ('Saudi Arabia', 'iso34000000'),\n",
2878 | " ('United Arab Emirates', 'iso9800000'),\n",
2879 | " ('Algeria', 'iso43000000'),\n",
2880 | " ('Morocco', 'iso36000000'),\n",
2881 | " ('Iraq', 'iso40000000'),\n",
2882 | " ('Sudan', 'iso43000000'),\n",
2883 | " ('Syria', 'iso17500000'),\n",
2884 | " ('Jordan', 'iso10000000'),\n",
2885 | " ('Palestine', 'iso5000000')\n",
2886 | "]"
2887 | ]
2888 | },
2889 | {
2890 | "cell_type": "code",
2891 | "execution_count": null,
2892 | "id": "ec570f25",
2893 | "metadata": {},
2894 | "outputs": [],
2895 | "source": []
2896 | },
2897 | {
2898 | "cell_type": "markdown",
2899 | "id": "c80bef4e",
2900 | "metadata": {},
2901 | "source": [
2902 | "## Extracting and Sorting Population Data from Embedded ISO Codes"
2903 | ]
2904 | },
2905 | {
2906 | "cell_type": "code",
2907 | "execution_count": 67,
2908 | "id": "cc6ddd8e",
2909 | "metadata": {},
2910 | "outputs": [
2911 | {
2912 | "data": {
2913 | "text/plain": [
2914 | "[('Egypt', 'iso110000000'),\n",
2915 | " ('Algeria', 'iso43000000'),\n",
2916 | " ('Sudan', 'iso43000000'),\n",
2917 | " ('Iraq', 'iso40000000'),\n",
2918 | " ('Morocco', 'iso36000000'),\n",
2919 | " ('Saudi Arabia', 'iso34000000'),\n",
2920 | " ('Syria', 'iso17500000'),\n",
2921 | " ('Jordan', 'iso10000000'),\n",
2922 | " ('United Arab Emirates', 'iso9800000'),\n",
2923 | " ('Palestine', 'iso5000000')]"
2924 | ]
2925 | },
2926 | "execution_count": 67,
2927 | "metadata": {},
2928 | "output_type": "execute_result"
2929 | }
2930 | ],
2931 | "source": [
2932 | "def get_population(pair):\n",
2933 | " counrty,population = pair\n",
2934 | " return int(population[3:])\n",
2935 | "\n",
2936 | "sorted(iso,key=get_population,reverse=True)"
2937 | ]
2938 | },
2939 | {
2940 | "cell_type": "code",
2941 | "execution_count": null,
2942 | "id": "7cab207a",
2943 | "metadata": {},
2944 | "outputs": [],
2945 | "source": []
2946 | },
2947 | {
2948 | "cell_type": "code",
2949 | "execution_count": null,
2950 | "id": "8c6a031b",
2951 | "metadata": {},
2952 | "outputs": [],
2953 | "source": []
2954 | },
2955 | {
2956 | "cell_type": "markdown",
2957 | "id": "706e400e",
2958 | "metadata": {},
2959 | "source": [
2960 | "_____"
2961 | ]
2962 | },
2963 | {
2964 | "cell_type": "markdown",
2965 | "id": "79689d04",
2966 | "metadata": {},
2967 | "source": [
2968 | "# Challenge: `sorted()`\n",
2969 | "\n",
2970 | "## Understanding ASCII values\n",
2971 | "\n",
2972 | "- We start by importing the `string` module and exploring the ASCII values for lowercase and uppercase letters."
2973 | ]
2974 | },
2975 | {
2976 | "cell_type": "code",
2977 | "execution_count": 68,
2978 | "id": "99707f49",
2979 | "metadata": {},
2980 | "outputs": [
2981 | {
2982 | "name": "stdout",
2983 | "output_type": "stream",
2984 | "text": [
2985 | "abcdefghijklmnopqrstuvwxyz\n",
2986 | "[97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122]\n"
2987 | ]
2988 | }
2989 | ],
2990 | "source": [
2991 | "import string\n",
2992 | "\n",
2993 | "# Lowercase ASCII values\n",
2994 | "print(string.ascii_lowercase) \n",
2995 | "lowercase_ascii_values = [ord(char) for char in string.ascii_lowercase]\n",
2996 | "print(lowercase_ascii_values)"
2997 | ]
2998 | },
2999 | {
3000 | "cell_type": "code",
3001 | "execution_count": null,
3002 | "id": "44045992",
3003 | "metadata": {},
3004 | "outputs": [],
3005 | "source": []
3006 | },
3007 | {
3008 | "cell_type": "code",
3009 | "execution_count": 69,
3010 | "id": "07f2bfb9",
3011 | "metadata": {},
3012 | "outputs": [
3013 | {
3014 | "name": "stdout",
3015 | "output_type": "stream",
3016 | "text": [
3017 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n",
3018 | "[65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]\n"
3019 | ]
3020 | }
3021 | ],
3022 | "source": [
3023 | "# Uppercase ASCII values\n",
3024 | "print(string.ascii_uppercase) \n",
3025 | "uppercase_ascii_values = [ord(char) for char in string.ascii_uppercase]\n",
3026 | "print(uppercase_ascii_values)"
3027 | ]
3028 | },
3029 | {
3030 | "cell_type": "markdown",
3031 | "id": "ae899dfb",
3032 | "metadata": {},
3033 | "source": [
3034 | "You can see that the ASCII values for uppercase letters are lower than those for lowercase letters. This means that if we sort by letters, uppercase letters will always be displayed before lowercase letters, as observed earlier.\n"
3035 | ]
3036 | },
3037 | {
3038 | "cell_type": "code",
3039 | "execution_count": null,
3040 | "id": "1c2c662a",
3041 | "metadata": {},
3042 | "outputs": [],
3043 | "source": []
3044 | },
3045 | {
3046 | "cell_type": "markdown",
3047 | "id": "a81d2b89",
3048 | "metadata": {},
3049 | "source": [
3050 | "## Creating a Country Class"
3051 | ]
3052 | },
3053 | {
3054 | "cell_type": "code",
3055 | "execution_count": 70,
3056 | "id": "b5a6a654",
3057 | "metadata": {},
3058 | "outputs": [],
3059 | "source": [
3060 | "class Country:\n",
3061 | " def __init__(self, name, population):\n",
3062 | " self.name = name\n",
3063 | " self.population = population\n",
3064 | " \n",
3065 | " def __repr__(self):\n",
3066 | " return f'Country({self.name},{self.population})'\n",
3067 | " \n",
3068 | " def __eq__(self, other):\n",
3069 | " return f'Country({self.name}, {self.population})' == f'Country({other.name}, {other.population})'"
3070 | ]
3071 | },
3072 | {
3073 | "cell_type": "markdown",
3074 | "id": "5b6334cc",
3075 | "metadata": {},
3076 | "source": [
3077 | "## Country List\n",
3078 | "- We define a list of tuples containing country names and their populations."
3079 | ]
3080 | },
3081 | {
3082 | "cell_type": "code",
3083 | "execution_count": 71,
3084 | "id": "f0f0d37e",
3085 | "metadata": {},
3086 | "outputs": [],
3087 | "source": [
3088 | "country_list = [\n",
3089 | " Country('Egypt', '110000000iso'),\n",
3090 | " Country('Saudi Arabia', '34000000iso'),\n",
3091 | " Country('United Arab Emirates', '9800000iso'),\n",
3092 | " Country('Algeria', '43000000iso'),\n",
3093 | " Country('Morocco', '36000000iso'),\n",
3094 | " Country('Iraq', '40000000iso'),\n",
3095 | " Country('Sudan', '43000000iso'),\n",
3096 | " Country('Syria', '17500000iso'),\n",
3097 | " Country('Jordan', '10000000iso'),\n",
3098 | " Country('Palestine', '5000000iso')\n",
3099 | "]"
3100 | ]
3101 | },
3102 | {
3103 | "cell_type": "markdown",
3104 | "id": "54882ad1",
3105 | "metadata": {},
3106 | "source": [
3107 | "## Helper Function: get_population\n",
3108 | "- We define a helper function to extract the numerical population from the population string."
3109 | ]
3110 | },
3111 | {
3112 | "cell_type": "code",
3113 | "execution_count": 72,
3114 | "id": "1df1847c",
3115 | "metadata": {},
3116 | "outputs": [],
3117 | "source": [
3118 | "def get_population(pair):\n",
3119 | " country, population = pair.name, pair.population\n",
3120 | " return int(population[:-3])"
3121 | ]
3122 | },
3123 | {
3124 | "cell_type": "markdown",
3125 | "id": "c134b670",
3126 | "metadata": {},
3127 | "source": [
3128 | "## Sorting the Country List\n",
3129 | "- Finally, we create a function to sort the country list first by population and then alphabetically by country name."
3130 | ]
3131 | },
3132 | {
3133 | "cell_type": "code",
3134 | "execution_count": 73,
3135 | "id": "721cabc3",
3136 | "metadata": {},
3137 | "outputs": [
3138 | {
3139 | "name": "stdout",
3140 | "output_type": "stream",
3141 | "text": [
3142 | "Country(Palestine,5000000iso)\n",
3143 | "Country(United Arab Emirates,9800000iso)\n",
3144 | "Country(Jordan,10000000iso)\n",
3145 | "Country(Syria,17500000iso)\n",
3146 | "Country(Saudi Arabia,34000000iso)\n",
3147 | "Country(Morocco,36000000iso)\n",
3148 | "Country(Iraq,40000000iso)\n",
3149 | "Country(Algeria,43000000iso)\n",
3150 | "Country(Sudan,43000000iso)\n",
3151 | "Country(Egypt,110000000iso)\n"
3152 | ]
3153 | }
3154 | ],
3155 | "source": [
3156 | "def get_sorted():\n",
3157 | " \"\"\"\n",
3158 | " Return the country list so that it is sorted first by population\n",
3159 | " and then alphabetically by country name.\n",
3160 | " \"\"\"\n",
3161 | " #result = sorted(country_list, key=lambda x: x.name.lower())\n",
3162 | " #return sorted(result,key=get_population)\n",
3163 | " return sorted(country_list, key=lambda x:(int(x.population[:-3]), x.name.lower()))\n",
3164 | "\n",
3165 | "# Print sorted countries\n",
3166 | "sorted_countries = get_sorted()\n",
3167 | "for country in sorted_countries:\n",
3168 | " print(country)"
3169 | ]
3170 | },
3171 | {
3172 | "cell_type": "code",
3173 | "execution_count": null,
3174 | "id": "4b55eee2",
3175 | "metadata": {},
3176 | "outputs": [],
3177 | "source": []
3178 | },
3179 | {
3180 | "cell_type": "code",
3181 | "execution_count": null,
3182 | "id": "aed80ad5",
3183 | "metadata": {},
3184 | "outputs": [],
3185 | "source": []
3186 | },
3187 | {
3188 | "cell_type": "markdown",
3189 | "id": "e0248e25",
3190 | "metadata": {},
3191 | "source": [
3192 | "-----------------\n",
3193 | "-----------------"
3194 | ]
3195 | },
3196 | {
3197 | "cell_type": "code",
3198 | "execution_count": null,
3199 | "id": "9e14c68f",
3200 | "metadata": {},
3201 | "outputs": [],
3202 | "source": []
3203 | },
3204 | {
3205 | "cell_type": "code",
3206 | "execution_count": null,
3207 | "id": "360cccc7",
3208 | "metadata": {},
3209 | "outputs": [],
3210 | "source": []
3211 | }
3212 | ],
3213 | "metadata": {
3214 | "kernelspec": {
3215 | "display_name": "Python 3 (ipykernel)",
3216 | "language": "python",
3217 | "name": "python3"
3218 | },
3219 | "language_info": {
3220 | "codemirror_mode": {
3221 | "name": "ipython",
3222 | "version": 3
3223 | },
3224 | "file_extension": ".py",
3225 | "mimetype": "text/x-python",
3226 | "name": "python",
3227 | "nbconvert_exporter": "python",
3228 | "pygments_lexer": "ipython3",
3229 | "version": "3.11.8"
3230 | }
3231 | },
3232 | "nbformat": 4,
3233 | "nbformat_minor": 5
3234 | }
3235 |
--------------------------------------------------------------------------------