diff --git a/.gitignore b/.gitignore index b6cb4c7..bfce384 100644 --- a/.gitignore +++ b/.gitignore @@ -3,31 +3,18 @@ *.pyd *.bin *.pkl -*.venv -*.idea -__pycache__ -.pytest_cache -.ruff_cache -# config & context -.vscode -.claude +**/.vscode/ +**/.claude/ +**/.idea/ +**/.venv/ +**/build/ +**/__pycache__/ +**/.pytest_cache/ +**/.ruff_cache/ +**/.logs/ +**/.tmp/ -# clang -/clang_2026/guides - -# builds -build - -# ai-notes & logs -gemini -CLAUDE.md - -# other dirs and files -*linux_commands -0x_c_extension -books -cloud -0x_problems -template-rules.md -ml-types.md +# fastapi/x-project/data +fastapi-projects/**/data/*.csv +fastapi-projects/**/data/*.json diff --git a/.ruff.toml b/.ruff.toml index 5d01075..cb3a15a 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -1,5 +1,20 @@ +# Ruff configuration file target-version = "py314" -extend-include = ["*.ipynb"] + +# Set line length limit to 120 (more modern & forgiving than 88) +line-length = 120 + +# Exclude virtual environments and cache directories +exclude = [ + ".venv", + "venv", + "__pycache__", + ".pytest_cache", + ".ruff_cache", + ".logs", +] [lint] -select = ["E", "F", "I"] \ No newline at end of file +select = ["E", "F", "I"] # E: errors, F: pyflakes, I: isort(import sorting) +# Ignore line-too-long (E501) and module-import-not-at-top (E402 for notebooks) +ignore = ["E501", "E402"] \ No newline at end of file diff --git a/00_basics/00_init.py b/00_basics/00_init.py index 17e5e4e..9109ed7 100644 --- a/00_basics/00_init.py +++ b/00_basics/00_init.py @@ -3,7 +3,7 @@ print("Hello, world") # variables -name = "Saqib, Bedar" # type string -age = 22 # integer -height = 5.4 # float -is_student = True # bool +name = "Saqib, Bedar" # type string +age = 22 # integer +height = 5.4 # float +is_student = True # bool diff --git a/00_basics/01_types.py b/00_basics/01_types.py index 83fa7a4..8eb143a 100644 --- a/00_basics/01_types.py +++ b/00_basics/01_types.py @@ -1,5 +1,5 @@ name = "Alice" age = 25 -print(type(name)) # -print(type(age)) # \ No newline at end of file +print(type(name)) # +print(type(age)) # diff --git a/00_basics/02_input.py b/00_basics/02_input.py index 8428542..805956c 100644 --- a/00_basics/02_input.py +++ b/00_basics/02_input.py @@ -1,3 +1,3 @@ name = input("What's your name?") -print(f"Hello, {name}!") \ No newline at end of file +print(f"Hello, {name}!") diff --git a/00_basics/03_typecasting.py b/00_basics/03_typecasting.py index 6ec7072..1e6a039 100644 --- a/00_basics/03_typecasting.py +++ b/00_basics/03_typecasting.py @@ -1,8 +1,8 @@ # age = input("What's your age?") # print(age+1) # Error: can't add string and number -# input() function always return string so we need to +# input() function always return string so we need to age = int(input("What's your age?")) -print(f"You will be {age+1} next year!") \ No newline at end of file +print(f"You will be {age + 1} next year!") diff --git a/00_basics/04_operators.py b/00_basics/04_operators.py index 8dad645..0fc305f 100644 --- a/00_basics/04_operators.py +++ b/00_basics/04_operators.py @@ -2,33 +2,33 @@ a = 10 b = 3 -print(a + b) # 13 → Addition -print(a - b) # 7 → Subtraction -print(a * b) # 30 → Multiplication -print(a / b) # 3.3333 → Division (always returns float) +print(a + b) # 13 → Addition +print(a - b) # 7 → Subtraction +print(a * b) # 30 → Multiplication +print(a / b) # 3.3333 → Division (always returns float) print(a // b) # 3 → Floor division (removes decimal) -print(a % b) # 1 → Modulus (remainder) -print(a ** b) # 1000 → Exponent (10 to the power of 3) +print(a % b) # 1 → Modulus (remainder) +print(a**b) # 1000 → Exponent (10 to the power of 3) # Comparison Operators x = 10 y = 20 -print(x == y) # False → Equal to -print(x != y) # True → Not equal to -print(x > y) # False → Greater than -print(x < y) # True → Less than +print(x == y) # False → Equal to +print(x != y) # True → Not equal to +print(x > y) # False → Greater than +print(x < y) # True → Less than print(x >= 10) # True → Greater than or equal -print(x <= 9) # False → Less than or equal +print(x <= 9) # False → Less than or equal # Assignment Operators score = 100 -score += 10 # same as score = score + 10 → 110 -score -= 5 # same as score = score - 5 → 105 -score *= 2 # same as score = score * 2 → 210 -score //= 3 # same as score = score // 3 → 70 +score += 10 # same as score = score + 10 → 110 +score -= 5 # same as score = score - 5 → 105 +score *= 2 # same as score = score * 2 → 210 +score //= 3 # same as score = score // 3 → 70 # Example usage @@ -48,15 +48,15 @@ age = 20 has_id = True -print(age >= 18 and has_id) # True → both are true -print(age < 18 or has_id) # True → one is true -print(not has_id) # False → flips True to False +print(age >= 18 and has_id) # True → both are true +print(age < 18 or has_id) # True → one is true +print(not has_id) # False → flips True to False # Identity Operators x = None -print(x is None) # True +print(x is None) # True print(x is not None) # False @@ -64,6 +64,6 @@ name = "Alice" fruits = ["apple", "banana", "mango"] -print("A" in name) # True -print("mango" in fruits) # True -print("grape" not in fruits) # True \ No newline at end of file +print("A" in name) # True +print("mango" in fruits) # True +print("grape" not in fruits) # True diff --git a/00_basics/05_conditionals.py b/00_basics/05_conditionals.py index 284ee89..1979b6f 100644 --- a/00_basics/05_conditionals.py +++ b/00_basics/05_conditionals.py @@ -32,4 +32,4 @@ print("Withdraw balance is too small") else: balance -= withdraw - print(f"Withdrawn! Remaining balance: {balance}") \ No newline at end of file + print(f"Withdrawn! Remaining balance: {balance}") diff --git a/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/00_integers_floats/integers.ipynb b/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/00_integers_floats/integers.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/00_integers_floats/integers.ipynb +++ b/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/00_integers_floats/integers.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/01_strings/strings.ipynb b/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/01_strings/strings.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/01_strings/strings.ipynb +++ b/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/01_strings/strings.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/02_Booleans/booleans.ipynb b/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/02_Booleans/booleans.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/02_Booleans/booleans.ipynb +++ b/0x_datastructures/01_builtin_datastructures/00_pdt_building_blocks/02_Booleans/booleans.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/00_list.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/00_list.py index 3179929..e9d115c 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/00_list.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/00_list.py @@ -1,7 +1,7 @@ -num_list: int = [1, 2, 3, 4, 5] +num_list: list[int] = [1, 2, 3, 4, 5] # print full list -print(num_list) # Output: [1, 2, 3, 4, 5] +print(num_list) # Output: [1, 2, 3, 4, 5] # loop over list for num in num_list: @@ -12,4 +12,4 @@ # 2 # 3 # 4 -# 5 \ No newline at end of file +# 5 diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/01_enumrate.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/01_enumrate.py index 0d4c7a2..9028357 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/01_enumrate.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/01_enumrate.py @@ -1,6 +1,6 @@ numList = [10, 20, 30] -print(f"{" Tuples ".center(36, "=")}") +print(f"{' Tuples '.center(36, '=')}") for num in enumerate(numList): print(num) @@ -13,7 +13,7 @@ """ # accessing values separate, index, and actual entry at index -print(f" Debug ".center(36, "=")) +print(" Debug ".center(36, "=")) for i, num in enumerate(numList): print(f"{i=}, {num=}") @@ -22,4 +22,4 @@ i=0, num=10 i=1, num=20 i=2, num=30 -""" \ No newline at end of file +""" diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/2D_list.ipynb b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/2D_list.ipynb index df311f9..69621de 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/2D_list.ipynb +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/2D_list.ipynb @@ -33,11 +33,7 @@ "metadata": {}, "outputs": [], "source": [ - "matrix = [\n", - " [1, 2, 3],\n", - " [4, 5, 6],\n", - " [7, 8, 9]\n", - "]" + "matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]" ] }, { @@ -97,11 +93,7 @@ "metadata": {}, "outputs": [], "source": [ - "matrix = [\n", - " [1, 2, 3],\n", - " [4, 5, 6],\n", - " [7, 8, 9]\n", - "]" + "matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]" ] }, { @@ -221,11 +213,11 @@ } ], "source": [ - "bad = [[0]*3]*3\n", - "print(id(bad[0]) == id(bad[1])) # True ← Same object!\n", + "bad = [[0] * 3] * 3\n", + "print(id(bad[0]) == id(bad[1])) # True ← Same object!\n", "\n", - "good = [[0]*3 for _ in range(3)]\n", - "print(id(good[0]) == id(good[1])) # False ← Different objects!" + "good = [[0] * 3 for _ in range(3)]\n", + "print(id(good[0]) == id(good[1])) # False ← Different objects!" ] }, { @@ -310,7 +302,7 @@ "flat = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "rows, cols = 3, 3\n", "\n", - "matrix = [flat[i*cols:(i+1)*cols] for i in range(rows)]\n", + "matrix = [flat[i * cols : (i + 1) * cols] for i in range(rows)]\n", "\n", "print(matrix)" ] @@ -414,15 +406,11 @@ } ], "source": [ - "matrix = [\n", - " [10, 20, 30],\n", - " [40, 50, 60],\n", - " [70, 80, 90]\n", - "]\n", + "matrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]\n", "\n", - "matrix[0][0] # 10 (Row 0, Col 0)\n", - "matrix[1][2] # 50 (Row 1, Col 2)\n", - "matrix[2][1] # 80 (Row 2, Col 3)" + "matrix[0][0] # 10 (Row 0, Col 0)\n", + "matrix[1][2] # 50 (Row 1, Col 2)\n", + "matrix[2][1] # 80 (Row 2, Col 3)" ] }, { @@ -480,8 +468,10 @@ } ], "source": [ - "print(matrix[-1]) # last row [70, 80, 90]\n", - "print(matrix[-1][-1]) # first [-1] return last row and second gives us last element in that list (90 (last row, last col))" + "print(matrix[-1]) # last row [70, 80, 90]\n", + "print(\n", + " matrix[-1][-1]\n", + ") # first [-1] return last row and second gives us last element in that list (90 (last row, last col))" ] }, { @@ -502,7 +492,7 @@ } ], "source": [ - "matrix[-1][0] # 70 (last row, first col)" + "matrix[-1][0] # 70 (last row, first col)" ] }, { @@ -521,10 +511,10 @@ "outputs": [], "source": [ "# Entire row (easy — it's just a list)\n", - "row1 = matrix[1] # [40, 50, 60]\n", + "row1 = matrix[1] # [40, 50, 60]\n", "\n", "# Entire column (must extract)\n", - "col1 = [row[1] for row in matrix] # [20, 50, 80]" + "col1 = [row[1] for row in matrix] # [20, 50, 80]" ] }, { @@ -585,11 +575,7 @@ "metadata": {}, "outputs": [], "source": [ - "matrix = [\n", - " [1, 2, 3],\n", - " [4, 5, 6],\n", - " [7, 8, 9]\n", - "]" + "matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]" ] }, { @@ -620,7 +606,7 @@ "# Standard nested loop\n", "for i in range(len(matrix)):\n", " for j in range(len(matrix[0])):\n", - " print(matrix[i][j], end=' ')\n", + " print(matrix[i][j], end=\" \")\n", " print()" ] }, @@ -655,12 +641,12 @@ "source": [ "for i in range(len(matrix)):\n", " for j in range(len(matrix[0])):\n", - " print(matrix[j][i], end=' ') # just swap matrix[i][j] -> matrix[j][i]\n", + " print(matrix[j][i], end=\" \") # just swap matrix[i][j] -> matrix[j][i]\n", " print()\n", "\n", "\n", "# separator\n", - "print(\"-\"*4)\n", + "print(\"-\" * 4)\n", "\n", "# Alternative solution\n", "\n", @@ -668,7 +654,7 @@ "for j in range(len(matrix[0])):\n", " # get matrix height (row size)\n", " for i in range(len(matrix)):\n", - " print(matrix[i][j], end=' ')\n", + " print(matrix[i][j], end=\" \")\n", " print()" ] }, @@ -787,7 +773,7 @@ ], "source": [ "# Method 2: List comprehension (the pythonic way)\n", - "flat = [val for row in matrix for val in row] # Read left-to-right like nested loops!\n", + "flat = [val for row in matrix for val in row] # Read left-to-right like nested loops!\n", "print(flat)" ] }, @@ -808,7 +794,7 @@ "source": [ "# Method 3: sum() with empty start (clever but O(n²) — avoid for big data)\n", "flat = sum(matrix, [])\n", - "print(flat) \n", + "print(flat)\n", "# [[1,2,3]] + [] = [1,2,3], then + [4,5,6]..." ] }, @@ -835,11 +821,7 @@ "metadata": {}, "outputs": [], "source": [ - "matrix = [\n", - " [1, 2, 3],\n", - " [4, 5, 6],\n", - " [7, 8, 9]\n", - "]" + "matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]" ] }, { @@ -886,7 +868,7 @@ ], "source": [ "# Anti-Diagonals\n", - "anti_diag = [matrix[i][n-1-i] for i in range(len(matrix))]\n", + "anti_diag = [matrix[i][n - 1 - i] for i in range(len(matrix))]\n", "print(anti_diag)" ] } diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_memory_representation.md b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_memory_representation.md index 85e9b59..36bcc5e 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_memory_representation.md +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_memory_representation.md @@ -79,11 +79,7 @@ x A 2D list is just a list of lists. ```py -x = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] -] +x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` At the memory level, the outer list points to three inner lists. Each inner list then points to its own elements. diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_ref_trap.md b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_ref_trap.md index 53ae95b..dccc03d 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_ref_trap.md +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_ref_trap.md @@ -205,11 +205,7 @@ print(m) produces: ```python -[ - [99, 0, 0], - [7, 7, 7], - [99, 0, 0] -] +[[99, 0, 0], [7, 7, 7], [99, 0, 0]] ``` Or simply: diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_trap.md b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_trap.md index 28ec4ef..e23d285 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_trap.md +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/1d_2d_list_trap.md @@ -231,9 +231,7 @@ x[2] ──┘ Therefore, `print(x)` gives: ```py -[[0, 99, 0], - [0, 99, 0], - [0, 99, 0]] +[[0, 99, 0], [0, 99, 0], [0, 99, 0]] ``` It looks like three rows changed, but only one list changed. All three outer positions were pointing at it. diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/Questions/list_output_question1.ipynb b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/Questions/list_output_question1.ipynb index 4d9851b..d125164 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/Questions/list_output_question1.ipynb +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/Questions/list_output_question1.ipynb @@ -15,7 +15,7 @@ } ], "source": [ - "x = [0]*5 # repeat five references\n", + "x = [0] * 5 # repeat five references\n", "\n", "print(x)" ] @@ -35,7 +35,7 @@ } ], "source": [ - "m = [[0]*3]*3 \n", + "m = [[0] * 3] * 3\n", "print(m)\n", "\n", "# breakdown of syntax: [0]*3 gives [0, 0, 0] and wrap it in []*3 -> [[0, 0, 0]]*3 same operation repeat refs about 3 times which gives us [[0, 0, 0], [0, 0, 0], [0, 0, 0]]." @@ -64,7 +64,7 @@ "metadata": {}, "outputs": [], "source": [ - "m = [[0]*3]*3\n", + "m = [[0] * 3] * 3\n", "m[1] = [7, 7, 7]\n", "m[0][0] = 99\n", "print(m)" diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/Questions/list_output_question2.ipynb b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/Questions/list_output_question2.ipynb index 9f21b2a..bd6a298 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/Questions/list_output_question2.ipynb +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/Questions/list_output_question2.ipynb @@ -21,6 +21,7 @@ " x.append(1)\n", " return x\n", "\n", + "\n", "print(f())\n", "print(f())\n", "print(f())" @@ -64,6 +65,7 @@ " x.append([])\n", " return x\n", "\n", + "\n", "a = f()\n", "b = f()\n", "\n", diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/python_mutable_default_argument_trap.md b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/python_mutable_default_argument_trap.md index 88186d1..92f274c 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/python_mutable_default_argument_trap.md +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/interview/python_mutable_default_argument_trap.md @@ -457,9 +457,7 @@ print(m) produces: ``` python -[[0, 0, 0, 99], - [0, 0, 0, 99], - [0, 0, 0, 99]] +[[0, 0, 0, 99], [0, 0, 0, 99], [0, 0, 0, 99]] ``` Again, only **one list** was modified. @@ -629,8 +627,7 @@ b ──┘ ### Mutable default argument ``` python -def f(x=[]): - ... +def f(x=[]): ... ``` Multiple calls without an explicit argument reuse the same default list. diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/list.ipynb b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/list.ipynb index ad32b7f..c8db26e 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/list.ipynb +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/list.ipynb @@ -61,20 +61,20 @@ "b = list()\n", "\n", "# from iterable\n", - "c = list(\"abc\") # ['a', 'b', 'c']\n", - "d = list((1, 2, 3)) # [1, 2, 3]\n", - "c = list(range(5)) # [0, 1, 2, 3, 4]\n", + "c = list(\"abc\") # ['a', 'b', 'c']\n", + "d = list((1, 2, 3)) # [1, 2, 3]\n", + "c = list(range(5)) # [0, 1, 2, 3, 4]\n", "\n", "# With repetition\n", - "f = [0] * 5 # [0, 0, 0, 0, 0]\n", - "g = [[0]] * 3 # [[0], [0], [0]] <- All inner list are SAME object!\n", + "f = [0] * 5 # [0, 0, 0, 0, 0]\n", + "g = [[0]] * 3 # [[0], [0], [0]] <- All inner list are SAME object!\n", "\n", "# Fixed values\n", - "h = [0 for _ in range(5)] # [0, 0, 0, 0, 0]\n", + "h = [0 for _ in range(5)] # [0, 0, 0, 0, 0]\n", "\n", "# From user input (strings split)\n", - "data = \"10 20 30\".split() # ['10', '20', '30']\n", - "nums = list(map(int, data)) # [10, 20, 30]" + "data = \"10 20 30\".split() # ['10', '20', '30']\n", + "nums = list(map(int, data)) # [10, 20, 30]" ] }, { @@ -100,19 +100,19 @@ "metadata": {}, "outputs": [], "source": [ - "lst = ['a', 'b', 'c', 'd', 'e']\n", + "lst = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n", "\n", "# positive indices: 0 to len-1\n", - "lst[0] # 'a'\n", - "lst[3] # 'd'\n", + "lst[0] # 'a'\n", + "lst[3] # 'd'\n", "\n", "# Negative indices: -1 is last, -len is first\n", - "lst[-1] # 'e'\n", - "lst[-2] # 'd'\n", - "lst[-5] # 'a'\n", + "lst[-1] # 'e'\n", + "lst[-2] # 'd'\n", + "lst[-5] # 'a'\n", "\n", "# Out of range -> IndexError\n", - "lst[10] # IndexError" + "lst[10] # IndexError" ] }, { @@ -145,24 +145,24 @@ "lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "\n", "# Basic slice\n", - "lst[2:5] # [2, 3, 4] (💡: start from index 2 and stop before index 5) \n", - "lst[:5] # [0, 1, 2, 3, 4] (start defaults to 0)\n", - "lst[6:] # [6, 7, 8, 9] (stop defaults to end)\n", - "lst[:] # [0..9] (full copy!)\n", + "lst[2:5] # [2, 3, 4] (💡: start from index 2 and stop before index 5)\n", + "lst[:5] # [0, 1, 2, 3, 4] (start defaults to 0)\n", + "lst[6:] # [6, 7, 8, 9] (stop defaults to end)\n", + "lst[:] # [0..9] (full copy!)\n", "\n", "# Negative indices in slice\n", - "lst[-3:-1] # [7, 8] (-3 is 7, -1 is 9, exclusive)\n", - "lst[-5:] # [5, 6, 7, 8, 9] (💡: start from -ve index 5 till last index)\n", + "lst[-3:-1] # [7, 8] (-3 is 7, -1 is 9, exclusive)\n", + "lst[-5:] # [5, 6, 7, 8, 9] (💡: start from -ve index 5 till last index)\n", "\n", - "# Step size (stride) \n", - "lst[::2] # [0, 2, 4, 6, 8] (every 2nd)\n", - "lst[1::2] # [1, 3, 5, 7, 9]\n", - "lst[::-1] # [9, 8, 7, ..., 0] (REVERSED!)\n", - "lst[::-2] # [9, 7, 5, 3, 1] (reversed every 2nd)\n", + "# Step size (stride)\n", + "lst[::2] # [0, 2, 4, 6, 8] (every 2nd)\n", + "lst[1::2] # [1, 3, 5, 7, 9]\n", + "lst[::-1] # [9, 8, 7, ..., 0] (REVERSED!)\n", + "lst[::-2] # [9, 7, 5, 3, 1] (reversed every 2nd)\n", "\n", "# Negative step: start must be > stop\n", - "lst[5:1:-1] # [5, 4, 3, 2] (walk backwards)\n", - "lst[8:3:-2] # [8, 6, 4] (backwards, step 2)" + "lst[5:1:-1] # [5, 4, 3, 2] (walk backwards)\n", + "lst[8:3:-2] # [8, 6, 4] (backwards, step 2)" ] }, { @@ -191,33 +191,33 @@ "lst = [3, 1, 4, 1, 5]\n", "\n", "# Adding\n", - "lst.append(9) # [3, 1, 4, 1, 5, 9] → O(1) amortized\n", - "lst.extend([2, 6]) # [..., 9, 2, 6] → O(k)\n", + "lst.append(9) # [3, 1, 4, 1, 5, 9] → O(1) amortized\n", + "lst.extend([2, 6]) # [..., 9, 2, 6] → O(k)\n", "\n", "# Removing\n", - "lst.remove(1) # Removes FIRST '1' → O(n)\n", - "x = lst.pop() # Removes & returns last → O(1)\n", - "x = lst.pop(2) # Removes & returns idx 2→ O(n)\n", - "lst.insert(2, 99) # Insert 99 at index 2 → O(n)\n", - "lst.clear() # Empties list → O(1)\n", + "lst.remove(1) # Removes FIRST '1' → O(n)\n", + "x = lst.pop() # Removes & returns last → O(1)\n", + "x = lst.pop(2) # Removes & returns idx 2→ O(n)\n", + "lst.insert(2, 99) # Insert 99 at index 2 → O(n)\n", + "lst.clear() # Empties list → O(1)\n", "\n", "# Searching\n", - "idx = lst.index(4) # First occurrence of 4 → O(n)\n", - "cnt = lst.count(1) # How many 1s? → O(n)\n", + "idx = lst.index(4) # First occurrence of 4 → O(n)\n", + "cnt = lst.count(1) # How many 1s? → O(n)\n", "\n", "# Ordering\n", "# In-place: it mutates the existing list object. It does not create a brand new list.\n", - "lst.sort() # In-place ascending → TimSort: Best case O(n), worst case O(n log n)\n", - "lst.sort(reverse=True)# In-place descending\n", - "lst.reverse() # In-place reverse → O(n)\n", + "lst.sort() # In-place ascending → TimSort: Best case O(n), worst case O(n log n)\n", + "lst.sort(reverse=True) # In-place descending\n", + "lst.reverse() # In-place reverse → O(n)\n", "\n", "# Copying\n", - "new = lst.copy() # Shallow copy\n", - "new = lst[:] # Same thing (slice copy)\n", - "new = list(lst) # Same thing\n", + "new = lst.copy() # Shallow copy\n", + "new = lst[:] # Same thing (slice copy)\n", + "new = list(lst) # Same thing\n", "\n", "# Length\n", - "len(lst) # O(1)" + "len(lst) # O(1)" ] }, { @@ -251,8 +251,8 @@ "metadata": {}, "outputs": [], "source": [ - "a = [1, 2] + [3, 4] # [1, 2, 3, 4] (creates NEW list)\n", - "b = [1, 2] * 3 # [1, 2, 1, 2, 1, 2] (repeats)" + "a = [1, 2] + [3, 4] # [1, 2, 3, 4] (creates NEW list)\n", + "b = [1, 2] * 3 # [1, 2, 1, 2, 1, 2] (repeats)" ] }, { @@ -270,8 +270,8 @@ "metadata": {}, "outputs": [], "source": [ - "x = 3 in [1, 2, 3] # True → O(n)\n", - "y = 10 not in [1, 2, 3] # True" + "x = 3 in [1, 2, 3] # True → O(n)\n", + "y = 10 not in [1, 2, 3] # True" ] }, { @@ -302,12 +302,12 @@ "source": [ "nums = [3, 1, 4, 1, 5]\n", "\n", - "sum(nums) # 14\n", - "min(nums) # 1\n", - "max(nums) # 5\n", - "len(nums) # 5\n", - "all(nums) # True (all truthy)\n", - "any([0, 0, 5]) # True (any truthy)" + "sum(nums) # 14\n", + "min(nums) # 1\n", + "max(nums) # 5\n", + "len(nums) # 5\n", + "all(nums) # True (all truthy)\n", + "any([0, 0, 5]) # True (any truthy)" ] }, { @@ -328,8 +328,8 @@ "a, b, c = [1, 2, 3]\n", "\n", "# Star unpacking\n", - "first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]\n", - "first, *mid, last = [1,2,3,4,5] # first=1, mid=[2,3,4], last=5\n", + "first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]\n", + "first, *mid, last = [1, 2, 3, 4, 5] # first=1, mid=[2,3,4], last=5\n", "\n", "# Ignore with _\n", "a, _, c = [1, 2, 3]" @@ -364,14 +364,14 @@ } ], "source": [ - "for i, val in enumerate(['a', 'b', 'c']):\n", + "for i, val in enumerate([\"a\", \"b\", \"c\"]):\n", " print(i, val)\n", "\n", "# separator\n", - "print(\"-\"*5)\n", + "print(\"-\" * 5)\n", "\n", "# Start from custom index\n", - "for i, val in enumerate(['a', 'b', 'c'], start=1):\n", + "for i, val in enumerate([\"a\", \"b\", \"c\"], start=1):\n", " print(i, val)" ] }, @@ -400,7 +400,7 @@ } ], "source": [ - "names = ['Alice', 'Bob', 'Carol']\n", + "names = [\"Alice\", \"Bob\", \"Carol\"]\n", "ages = [25, 30, 35]\n", "\n", "for name, age in zip(names, ages):\n", @@ -428,7 +428,7 @@ "from itertools import zip_longest\n", "\n", "for a, b in zip_longest([1, 2], [1, 2, 3], fillvalue=0):\n", - " print(a,b)" + " print(a, b)" ] }, { @@ -525,7 +525,7 @@ "\n", "width = 2 # Width of each row\n", "\n", - "matrix = [flat[start:start+width] for start in range(0, len(flat), width)]\n", + "matrix = [flat[start : start + width] for start in range(0, len(flat), width)]\n", "\n", "# breakdown\n", "\"\"\"\n", @@ -546,8 +546,8 @@ "\n", "import numpy as np\n", "\n", - "matrix = np.array(flat).reshape(3, 2) # pure numpy\n", - "matrix = np.array(flat).reshape(3, 2).tolist() # convert back to python list\n", + "matrix = np.array(flat).reshape(3, 2) # pure numpy\n", + "matrix = np.array(flat).reshape(3, 2).tolist() # convert back to python list\n", "# [[1, 2], [3, 4], [5, 6]]" ] }, @@ -579,7 +579,7 @@ "metadata": {}, "outputs": [], "source": [ - "sums = [x+y for x in [1, 2] for y in [10, 20]]\n", + "sums = [x + y for x in [1, 2] for y in [10, 20]]\n", "# [11, 21, 12, 22]" ] }, @@ -638,7 +638,7 @@ } ], "source": [ - "lst = ['a', 'b', 'c', 'd']\n", + "lst = [\"a\", \"b\", \"c\", \"d\"]\n", "\n", "# By index\n", "for i in range(len(lst)):\n", @@ -662,8 +662,10 @@ "print(\"-\" * 5)\n", "\n", "# Multiple lists\n", - "for a, b in zip([1, 2], [1,2,3]):\n", - " print(a, b) # 🪧: look list1 < list2 and zip stops when both list values mismatch and its applicable on both even if list1 would have been > list2 still same rule applies. To avoid this you can use zip_longest from itertools and utilize fillvalue=any. " + "for a, b in zip([1, 2], [1, 2, 3]):\n", + " print(\n", + " a, b\n", + " ) # 🪧: look list1 < list2 and zip stops when both list values mismatch and its applicable on both even if list1 would have been > list2 still same rule applies. To avoid this you can use zip_longest from itertools and utilize fillvalue=any." ] }, { @@ -685,16 +687,16 @@ "\n", "while stack:\n", " item = stack.pop()\n", - " print(item) # 3, 2, 1\n", + " print(item) # 3, 2, 1\n", "\n", "# Iterators Under the Hood\n", "lst = [1, 2, 3]\n", "it = iter(lst)\n", "\n", - "next(it) # 1\n", - "next(it) # 2\n", - "next(it) # 3\n", - "next(it) # StopIteration exception!" + "next(it) # 1\n", + "next(it) # 2\n", + "next(it) # 3\n", + "next(it) # StopIteration exception!" ] }, { @@ -707,7 +709,7 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": null, "id": "f1ddab80", "metadata": {}, "outputs": [], @@ -725,7 +727,7 @@ "# [2, 4]\n", "\n", "# reduce: cumulative computation\n", - "product = reduce(lambda a, b: a * b, nums)\n", + "result = reduce(lambda a, b: a * b, nums)\n", "# 120 (1*2*3*4*5)\n", "\n", "# NOTE: Prefer list comprehensions over map/filter in Python!\n", @@ -755,7 +757,7 @@ } ], "source": [ - "from itertools import permutations, combinations, product, chain\n", + "from itertools import chain, combinations, permutations, product\n", "\n", "print(list(permutations([1, 2, 3], 2)))" ] @@ -794,7 +796,7 @@ ], "source": [ "# cartesian product\n", - "print(list(product([1, 2], ['a', 'b'])))" + "print(list(product([1, 2], [\"a\", \"b\"])))" ] }, { @@ -849,12 +851,12 @@ "# WRONG: All rows reference same inner list\n", "wrong = [[0] * 3] * 3\n", "wrong[0][0] = 99\n", - "print(wrong) # [[99, 0, 0], [99, 0, 0], [99, 0, 0]] ← Oops!\n", + "print(wrong) # [[99, 0, 0], [99, 0, 0], [99, 0, 0]] ← Oops!\n", "\n", "# RIGHT: Independent inner lists\n", "right = [[0 for _ in range(3)] for _ in range(3)]\n", "right[0][0] = 99\n", - "print(right) # [[99, 0, 0], [0, 0, 0], [0, 0, 0]]" + "print(right) # [[99, 0, 0], [0, 0, 0], [0, 0, 0]]" ] }, { @@ -876,7 +878,7 @@ "lst = [1, 2, 3, 4, 5]\n", "for item in lst:\n", " if item % 2 == 0:\n", - " lst.remove(item) # Skips elements! Bug!\n", + " lst.remove(item) # Skips elements! Bug!\n", "\n", "# SAFE: Iterate over a copy\n", "for item in lst[:]:\n", @@ -905,12 +907,12 @@ "import copy\n", "\n", "a = [[1, 2], [3, 4]]\n", - "b = a.copy() # Shallow: inner lists shared\n", - "c = copy.deepcopy(a) # Deep: fully independent\n", + "b = a.copy() # Shallow: inner lists shared\n", + "c = copy.deepcopy(a) # Deep: fully independent\n", "\n", "b[0][0] = 99\n", - "print(a[0][0]) # 99 (affected!)\n", - "print(c[0][0]) # 1 (unaffected)" + "print(a[0][0]) # 99 (affected!)\n", + "print(c[0][0]) # 1 (unaffected)" ] }, { diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/list_test.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/list_test.py index c8a3692..2ff9298 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/list_test.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/list_test.py @@ -12,4 +12,4 @@ x = [[[1, 2], [3, 4]], ["h", "o"]] -print(x[0][0][0]) \ No newline at end of file +print(x[0][0][0]) diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/tuples/00_list_of_tup.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/tuples/00_list_of_tup.py index c1ec6f0..89c4940 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/tuples/00_list_of_tup.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/00_lists/tuples/00_list_of_tup.py @@ -2,7 +2,7 @@ lst_tup = [ ("Saqib Bedar", 22, 5.4, "Islamabad", "Pakistan"), - ("John Doe", 40, 5.8, "unknown", "Some-country") + ("John Doe", 40, 5.8, "unknown", "Some-country"), ] for tup in lst_tup: @@ -13,10 +13,10 @@ # ('John Doe', 40, 5.8, 'unknown', 'Some-country') # destructing: unpacking directly inside loop -print(f"{"Name":<15} | {"Age":<6} | {"Height":<6} | {"City":<15} | {"Country"}") +print(f"{'Name':<15} | {'Age':<6} | {'Height':<6} | {'City':<15} | {'Country'}") print("-" * 70) for tup in lst_tup: # Explicit assignment unpacking name, age, height, city, country = tup - print(f"{name:<15} | {age:<6} | {height:<6} | {city:<15} | {country}") \ No newline at end of file + print(f"{name:<15} | {age:<6} | {height:<6} | {city:<15} | {country}") diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/01_tuples/tuples.ipynb b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/01_tuples/tuples.ipynb index 5809444..b3ca765 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/01_tuples/tuples.ipynb +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/01_tuples/tuples.ipynb @@ -76,8 +76,8 @@ } ], "source": [ - "not_a_tuple = (\"Apple\") # type: str\n", - "is_a_tuple = (\"Apple\",) # type: tuple\n", + "not_a_tuple = \"Apple\" # type: str\n", + "is_a_tuple = (\"Apple\",) # type: tuple\n", "\n", "print(type(not_a_tuple))\n", "print(type(is_a_tuple))" @@ -119,8 +119,8 @@ "source": [ "fruits_tuple = (\"Apple\", \"Banana\", \"Carrot\", \"Date\")\n", "\n", - "print(fruits_tuple[0]) # Apple\n", - "print(fruits_tuple[-1]) # Date (Negative indexing counts from the back)" + "print(fruits_tuple[0]) # Apple\n", + "print(fruits_tuple[-1]) # Date (Negative indexing counts from the back)" ] }, { @@ -208,7 +208,7 @@ "try:\n", " modes[0] = \"System\"\n", "except TypeError as te:\n", - " print(f\"Error: cannot assign a value at index 0.\")\n", + " print(\"Error: cannot assign a value at index 0.\")\n", " print(te)" ] }, @@ -255,14 +255,14 @@ "source": [ "point = (10, 20)\n", "\n", - "x, y = point # Unpacking\n", + "x, y = point # Unpacking\n", "\n", "print(x, y)\n", "\n", "scores = (1, 2, 2, 2, 3, 4, 5, 5, 5, 6)\n", "\n", "\n", - "print(\"-\"*10)\n", + "print(\"-\" * 10)\n", "\n", "# *rest: captures as list\n", "first, second, *rest = scores\n", @@ -272,7 +272,7 @@ "print(rest)\n", "\n", "\n", - "print(\"-\"*10)\n", + "print(\"-\" * 10)\n", "\n", "# or get another way\n", "first, *middle, last = scores\n", @@ -350,8 +350,8 @@ "source": [ "scores = (1, 2, 2, 2, 3, 4, 5, 5, 5, 6)\n", "\n", - "print(scores.count(2)) # frequency/appearance of 2 in scores tuple\n", - "print(scores.index(2)) # returns first matched item index" + "print(scores.count(2)) # frequency/appearance of 2 in scores tuple\n", + "print(scores.index(2)) # returns first matched item index" ] }, { diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_intro.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_intro.py index b2275be..3132100 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_intro.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_intro.py @@ -4,10 +4,10 @@ stop=1000 step=1 - syntax: range(start, stop, step) this is equivalent to an object like + syntax: range(start, stop, step) this is equivalent to an object like class myrange: - + def __init__(self, start : int = 0, stop : int, step : int = 1) -> None: self.start = start self.stop = stop @@ -17,17 +17,17 @@ def __init__(self, start : int = 0, stop : int, step : int = 1) -> None: Quick facts: - 1. If we pass single value then it is stop value - + 1. If we pass single value then it is stop value + for i in range(5) # here 5 is stop value, it stops before 5, range automatically set start = 0 - Mathematically: [0, 5) - + Mathematically: [0, 5) + Inclusive start and Exclusive stop 0 included | 5 excluded - + 2. range(3, 8) # start from 3 and stop before 8 output: 3, 4, 5, 6, 7 @@ -42,7 +42,7 @@ def __init__(self, start : int = 0, stop : int, step : int = 1) -> None: output: 2, 4, 6, 8 - internally: start += 2 + internally: start += 2 And condition is checked against stop is (current >= stop) @@ -62,12 +62,12 @@ def __init__(self, start : int = 0, stop : int, step : int = 1) -> None: 4 3 2 - 1 + 1 (0 not printed because at 0 it has to be stopped) - + for i in range(10, -1, -1) print(i) @@ -86,6 +86,6 @@ def __init__(self, start : int = 0, stop : int, step : int = 1) -> None: why 0? because -1 is stop value so it has keep iterate until it is checked against the stop value - -""" \ No newline at end of file + +""" diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_output_questions/01.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_output_questions/01.py index b31b3c2..0c77e1a 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_output_questions/01.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_output_questions/01.py @@ -4,4 +4,4 @@ """ output: range(1, 6) :- Why? Because range stores only three integers value i.e., range(start : int = 0, stop : int, step : int = 1) not all values. -""" \ No newline at end of file +""" diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_output_questions/02.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_output_questions/02.py index b94d327..e796aee 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_output_questions/02.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/00_output_questions/02.py @@ -1,2 +1,2 @@ for i in range(1, 10, -1): - print(i) \ No newline at end of file + print(i) diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/01_countup.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/01_countup.py index dfd7155..39ae492 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/01_countup.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/01_countup.py @@ -1,8 +1,8 @@ for i in range(2, 10, 2): print(i) -# Output: +# Output: # 2 # 4 # 6 -# 8 \ No newline at end of file +# 8 diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/02_list_conv.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/02_list_conv.py index 3edc82f..c601d31 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/02_list_conv.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/02_list_conv.py @@ -1,7 +1,7 @@ numbers: int = list(range(1, 10)) -print(numbers) # output: [1, 2, 3, 4, 5, 6, 7, 8, 9] +print(numbers) # output: [1, 2, 3, 4, 5, 6, 7, 8, 9] numbers = [range(1, 10)] -print(numbers) # Output: [range(1, 10)] +print(numbers) # Output: [range(1, 10)] -print(globals()) \ No newline at end of file +print(globals()) diff --git a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/03_list&range.py b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/03_list&range.py index f4d12ed..de6bf2f 100644 --- a/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/03_list&range.py +++ b/0x_datastructures/01_builtin_datastructures/01_linear_collections_sequences/02_range/03_list&range.py @@ -2,7 +2,7 @@ for i in range(len(fruits)): print(f"fruit name is [{fruits[i]}]") - + # fruit name is [Apple] # fruit name is [Banana] -# fruit name is [Carrot] \ No newline at end of file +# fruit name is [Carrot] diff --git a/0x_datastructures/01_builtin_datastructures/02_hashed_collections_unordered/00_dict/dict.ipynb b/0x_datastructures/01_builtin_datastructures/02_hashed_collections_unordered/00_dict/dict.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/01_builtin_datastructures/02_hashed_collections_unordered/00_dict/dict.ipynb +++ b/0x_datastructures/01_builtin_datastructures/02_hashed_collections_unordered/00_dict/dict.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/01_builtin_datastructures/02_hashed_collections_unordered/01_sets/sets.ipynb b/0x_datastructures/01_builtin_datastructures/02_hashed_collections_unordered/01_sets/sets.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/01_builtin_datastructures/02_hashed_collections_unordered/01_sets/sets.ipynb +++ b/0x_datastructures/01_builtin_datastructures/02_hashed_collections_unordered/01_sets/sets.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/00_namedtuple/namedtuple.ipynb b/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/00_namedtuple/namedtuple.ipynb index e390b5f..de86f4d 100644 --- a/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/00_namedtuple/namedtuple.ipynb +++ b/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/00_namedtuple/namedtuple.ipynb @@ -1,359 +1,362 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "b4916a85", - "metadata": {}, - "source": [ - "🪧 Please read [tuple](../../01_linear_collections_sequences/01_tuples/tuples.ipynb) first." - ] - }, - { - "cell_type": "markdown", - "id": "b7c98c18", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "8c756f0c", - "metadata": {}, - "source": [ - "# namedtuple\n", - "\n", - "A `namedtuple` is a factory function from Python's collections module that creates **immutable, lightweight, tuple-like objects** with named fields. This allows you to access elements using readable dot notation (e.g., `car.color`) instead of strictly relying on numeric indices (e.g., `car[0]`).\n", - "\n", - "It offers the memory efficiency of a standard tuple while making your code significantly cleaner and self-documenting" - ] - }, - { - "cell_type": "markdown", - "id": "25643868", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "2843198c", - "metadata": {}, - "source": [ - "### Basic Syntax & Creation\n", - "\n", - "To use `namedtuple`, you first define the template structure and then instantiate objects from it.\n", - "\n", - "```py\n", - "# first import it from collections \n", - "from collections import namedtuple\n", - "\n", - "# define template/structure\n", - "namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)\n", - "```\n", - "\n", - "**Argument Breakdown**:\n", - "\n", - "- `typename`: The string name of the new tuple subclass.\n", - "\n", - "- `field_names`: A list of strings `['x', 'y']`, a space-separated string `'x y'`, or a comma-separated string `'x, y'`.\n", - "\n", - "- `rename`: If `True`, invalid or duplicate field names are automatically replaced with positional names like `_1`.\n", - "\n", - "- `defaults`: An iterable of default values applied to the rightmost fields." - ] - }, - { - "cell_type": "markdown", - "id": "38632f70", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "3ffc59c7", - "metadata": {}, - "source": [ - "### Examples" - ] - }, - { - "cell_type": "markdown", - "id": "e3c8b65d", - "metadata": {}, - "source": [ - "**1. Basic Usage (Three different ways to define fields)**" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "1ab1afcb", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "10\n", - "20\n" - ] - } - ], - "source": [ - "from collections import namedtuple\n", - "\n", - "# Standard syntax using a list of strings\n", - "Point = namedtuple(\"Point\", ['x', 'y'])\n", - "\n", - "# Alternative: Space-separated string\n", - "Point = namedtuple(\"Point\", \"x y\")\n", - "\n", - "# Alternative: Comma-separated string\n", - "Point = namedtuple('Point', 'x, y')\n", - "\n", - "# Creating an instance\n", - "p = Point(10, 20)\n", - "\n", - "# Accessing values\n", - "print(p.x) # Output: 10 (Using name)\n", - "print(p[1]) # Output: 20 (Using index)" - ] - }, - { - "cell_type": "markdown", - "id": "db29eefd", - "metadata": {}, - "source": [ - "**2. Using Default Values**" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1c929925", - "metadata": {}, - "outputs": [], - "source": [ - "from collections import namedtuple\n", - "\n", - "# Defaults are applied from right to left (y gets 0, x gets 1)\n", - "Point = namedtuple('Point', ['x', 'y'], defaults=[1, 0])\n", - "\n", - "p1 = Point() # Point(x=1, y=0)\n", - "p2 = Point(5) # Point(x=5, y=0)\n", - "p3 = Point(x=7, y=8) # Point(x=7, y=8)" - ] - }, - { - "cell_type": "markdown", - "id": "27699025", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "ed1de945", - "metadata": {}, - "source": [ - "### Modern Alternative: Class-Based Syntax\n", - "\n", - "For modern Python code bases requiring type hints, use `typing.NamedTuple` instead:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f5819bd2", - "metadata": {}, - "outputs": [], - "source": [ - "from typing import NamedTuple\n", - "\n", - "class Point(NamedTuple):\n", - " x: int\n", - " y: int\n", - "\n", - " units: str = \"meters\" # Supports defaults and type hints" - ] - }, - { - "cell_type": "markdown", - "id": "f256a180", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "00b09487", - "metadata": {}, - "source": [ - "### More Examples" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "31f4ffe5", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Saqib Bedar\n", - "22\n" - ] - } - ], - "source": [ - "from collections import namedtuple\n", - "\n", - "# Define the structure and named attributes\n", - "Person = namedtuple('Person', ['name', 'age', 'height', 'city', 'country'])\n", - "\n", - "# Create a named tuple from above defined namedtuple datastructure\n", - "p1 = Person(\"Saqib Bedar\", 22, 5.4, \"Islamabad\", \"Pakistan\")\n", - "\n", - "# Access via attribute name\n", - "print(p1.name)\n", - "print(p1.age)" - ] - }, - { - "cell_type": "markdown", - "id": "082b0f81", - "metadata": {}, - "source": [ - "**Updating attributes**\n", - "\n", - "Python's `namedtuple` are immutable meaning they cannot be changed after creation. Hence, we cannot update attributes directly like `saqib.name = \"New name\"`.\n", - "\n", - "If you try to do that, Python will raise an `AttributeError`.\n", - "\n", - "Then how we do it? \n", - "\n", - "**Use the ._replace() Method**:\n", - "\n", - "This is the official and cleanest way. It does not modify the original object; instead, it creates a brand new tuple instance with the updated values." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "1cfebb1a", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Saqib Bedar\n", - "Islamabad\n" - ] - } - ], - "source": [ - "from collections import namedtuple\n", - "\n", - "# define structure for person\n", - "Person = namedtuple('Person', ['name', 'age', 'height', 'city', 'country'])\n", - "p1 = Person(\"Saqib\", 22, 5.4, \"Islamabad\", \"Pakistan\")\n", - "\n", - "# Create a new instance with the updated name\n", - "p1 = p1._replace(name=\"Saqib Bedar\")\n", - "\n", - "print(p1.name) # Output: New name\n", - "print(p1.city) # Output: Islamabad (other fields remain unchanged)" - ] - }, - { - "cell_type": "markdown", - "id": "db5f19b9", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "96107e6b", - "metadata": {}, - "source": [ - "### lternative: Use `class` or `dataclasses` (If you need mutability)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "69cfc69b", - "metadata": {}, - "outputs": [], - "source": [ - "class Person:\n", - " def __init__(self, name, age, height, city, country) -> None:\n", - " self.name = name\n", - " self.age = age\n", - " self.height = height\n", - " self.city = city\n", - " self.country = country\n", - "\n", - "# Or using dataclass with less boilerplate code\n", - "\n", - "from dataclasses import dataclass\n", - "\n", - "@dataclass\n", - "class Person:\n", - " name: str\n", - " age: int\n", - " height: float\n", - " city: str\n", - " country: str" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "95c4eb4b", - "metadata": {}, - "outputs": [], - "source": [ - "# Create the object\n", - "\n", - "p1 = Person(\"Saqib\", 22, 5.4, \"Islamabad\", \"Pakistan\")\n", - "\n", - "# Modify the attributes directly\n", - "p1.name = \"Saqib Bedar\"\n", - "p1.city = \"Larkana\"" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.14.4" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} +{ + "cells": [ + { + "cell_type": "markdown", + "id": "b4916a85", + "metadata": {}, + "source": [ + "🪧 Please read [tuple](../../01_linear_collections_sequences/01_tuples/tuples.ipynb) first." + ] + }, + { + "cell_type": "markdown", + "id": "b7c98c18", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "8c756f0c", + "metadata": {}, + "source": [ + "# namedtuple\n", + "\n", + "A `namedtuple` is a factory function from Python's collections module that creates **immutable, lightweight, tuple-like objects** with named fields. This allows you to access elements using readable dot notation (e.g., `car.color`) instead of strictly relying on numeric indices (e.g., `car[0]`).\n", + "\n", + "It offers the memory efficiency of a standard tuple while making your code significantly cleaner and self-documenting" + ] + }, + { + "cell_type": "markdown", + "id": "25643868", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "2843198c", + "metadata": {}, + "source": [ + "### Basic Syntax & Creation\n", + "\n", + "To use `namedtuple`, you first define the template structure and then instantiate objects from it.\n", + "\n", + "```py\n", + "# first import it from collections \n", + "from collections import namedtuple\n", + "\n", + "# define template/structure\n", + "namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)\n", + "```\n", + "\n", + "**Argument Breakdown**:\n", + "\n", + "- `typename`: The string name of the new tuple subclass.\n", + "\n", + "- `field_names`: A list of strings `['x', 'y']`, a space-separated string `'x y'`, or a comma-separated string `'x, y'`.\n", + "\n", + "- `rename`: If `True`, invalid or duplicate field names are automatically replaced with positional names like `_1`.\n", + "\n", + "- `defaults`: An iterable of default values applied to the rightmost fields." + ] + }, + { + "cell_type": "markdown", + "id": "38632f70", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "3ffc59c7", + "metadata": {}, + "source": [ + "### Examples" + ] + }, + { + "cell_type": "markdown", + "id": "e3c8b65d", + "metadata": {}, + "source": [ + "**1. Basic Usage (Three different ways to define fields)**" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "1ab1afcb", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n", + "20\n" + ] + } + ], + "source": [ + "from collections import namedtuple\n", + "\n", + "# Standard syntax using a list of strings\n", + "Point = namedtuple(\"Point\", [\"x\", \"y\"])\n", + "\n", + "# Alternative: Space-separated string\n", + "Point = namedtuple(\"Point\", \"x y\")\n", + "\n", + "# Alternative: Comma-separated string\n", + "Point = namedtuple(\"Point\", \"x, y\")\n", + "\n", + "# Creating an instance\n", + "p = Point(10, 20)\n", + "\n", + "# Accessing values\n", + "print(p.x) # Output: 10 (Using name)\n", + "print(p[1]) # Output: 20 (Using index)" + ] + }, + { + "cell_type": "markdown", + "id": "db29eefd", + "metadata": {}, + "source": [ + "**2. Using Default Values**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1c929925", + "metadata": {}, + "outputs": [], + "source": [ + "from collections import namedtuple\n", + "\n", + "# Defaults are applied from right to left (y gets 0, x gets 1)\n", + "Point = namedtuple(\"Point\", [\"x\", \"y\"], defaults=[1, 0])\n", + "\n", + "p1 = Point() # Point(x=1, y=0)\n", + "p2 = Point(5) # Point(x=5, y=0)\n", + "p3 = Point(x=7, y=8) # Point(x=7, y=8)" + ] + }, + { + "cell_type": "markdown", + "id": "27699025", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "ed1de945", + "metadata": {}, + "source": [ + "### Modern Alternative: Class-Based Syntax\n", + "\n", + "For modern Python code bases requiring type hints, use `typing.NamedTuple` instead:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f5819bd2", + "metadata": {}, + "outputs": [], + "source": [ + "from typing import NamedTuple\n", + "\n", + "\n", + "class Point(NamedTuple):\n", + " x: int\n", + " y: int\n", + "\n", + " units: str = \"meters\" # Supports defaults and type hints" + ] + }, + { + "cell_type": "markdown", + "id": "f256a180", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "00b09487", + "metadata": {}, + "source": [ + "### More Examples" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "31f4ffe5", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Saqib Bedar\n", + "22\n" + ] + } + ], + "source": [ + "from collections import namedtuple\n", + "\n", + "# Define the structure and named attributes\n", + "Person = namedtuple(\"Person\", [\"name\", \"age\", \"height\", \"city\", \"country\"])\n", + "\n", + "# Create a named tuple from above defined namedtuple datastructure\n", + "p1 = Person(\"Saqib Bedar\", 22, 5.4, \"Islamabad\", \"Pakistan\")\n", + "\n", + "# Access via attribute name\n", + "print(p1.name)\n", + "print(p1.age)" + ] + }, + { + "cell_type": "markdown", + "id": "082b0f81", + "metadata": {}, + "source": [ + "**Updating attributes**\n", + "\n", + "Python's `namedtuple` are immutable meaning they cannot be changed after creation. Hence, we cannot update attributes directly like `saqib.name = \"New name\"`.\n", + "\n", + "If you try to do that, Python will raise an `AttributeError`.\n", + "\n", + "Then how we do it? \n", + "\n", + "**Use the ._replace() Method**:\n", + "\n", + "This is the official and cleanest way. It does not modify the original object; instead, it creates a brand new tuple instance with the updated values." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "1cfebb1a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Saqib Bedar\n", + "Islamabad\n" + ] + } + ], + "source": [ + "from collections import namedtuple\n", + "\n", + "# define structure for person\n", + "Person = namedtuple(\"Person\", [\"name\", \"age\", \"height\", \"city\", \"country\"])\n", + "p1 = Person(\"Saqib\", 22, 5.4, \"Islamabad\", \"Pakistan\")\n", + "\n", + "# Create a new instance with the updated name\n", + "p1 = p1._replace(name=\"Saqib Bedar\")\n", + "\n", + "print(p1.name) # Output: New name\n", + "print(p1.city) # Output: Islamabad (other fields remain unchanged)" + ] + }, + { + "cell_type": "markdown", + "id": "db5f19b9", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "96107e6b", + "metadata": {}, + "source": [ + "### lternative: Use `class` or `dataclasses` (If you need mutability)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "69cfc69b", + "metadata": {}, + "outputs": [], + "source": [ + "class Person:\n", + " def __init__(self, name, age, height, city, country) -> None:\n", + " self.name = name\n", + " self.age = age\n", + " self.height = height\n", + " self.city = city\n", + " self.country = country\n", + "\n", + "\n", + "# Or using dataclass with less boilerplate code\n", + "\n", + "from dataclasses import dataclass\n", + "\n", + "\n", + "@dataclass\n", + "class Person:\n", + " name: str\n", + " age: int\n", + " height: float\n", + " city: str\n", + " country: str" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "95c4eb4b", + "metadata": {}, + "outputs": [], + "source": [ + "# Create the object\n", + "\n", + "p1 = Person(\"Saqib\", 22, 5.4, \"Islamabad\", \"Pakistan\")\n", + "\n", + "# Modify the attributes directly\n", + "p1.name = \"Saqib Bedar\"\n", + "p1.city = \"Larkana\"" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.14.4" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/01_deque/deque.ipynb b/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/01_deque/deque.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/01_deque/deque.ipynb +++ b/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/01_deque/deque.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/02_counter/counter.ipynb b/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/02_counter/counter.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/02_counter/counter.ipynb +++ b/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/02_counter/counter.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/03_default_dict/default_dict.ipynb b/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/03_default_dict/default_dict.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/03_default_dict/default_dict.ipynb +++ b/0x_datastructures/01_builtin_datastructures/03_containers_module_collections/03_default_dict/default_dict.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/02_custom_datastructures/00_stack/stack.ipynb b/0x_datastructures/02_custom_datastructures/00_stack/stack.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/02_custom_datastructures/00_stack/stack.ipynb +++ b/0x_datastructures/02_custom_datastructures/00_stack/stack.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/02_custom_datastructures/01_queue/queue.ipynb b/0x_datastructures/02_custom_datastructures/01_queue/queue.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/02_custom_datastructures/01_queue/queue.ipynb +++ b/0x_datastructures/02_custom_datastructures/01_queue/queue.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_datastructures/02_custom_datastructures/02_linkedlist/linkedlist.ipynb b/0x_datastructures/02_custom_datastructures/02_linkedlist/linkedlist.ipynb index e69de29..9ff4d73 100644 --- a/0x_datastructures/02_custom_datastructures/02_linkedlist/linkedlist.ipynb +++ b/0x_datastructures/02_custom_datastructures/02_linkedlist/linkedlist.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/0x_iterators/00_enumerate/00_intro.py b/0x_iterators/00_enumerate/00_intro.py index ce0ce5d..457d36e 100644 --- a/0x_iterators/00_enumerate/00_intro.py +++ b/0x_iterators/00_enumerate/00_intro.py @@ -43,9 +43,9 @@ for i, item in enumerate(["a", "b", "c"], start=-3): print(i, item) - + Output: - + -3 a -2 b -1 c @@ -70,11 +70,11 @@ def custom_enumerate(iterable, start=0) for item in iterable: yield (n, item) n += 1 - + list(custom_enumerate(["a", "b", "c"])) - output: [(0, 'a'), (1, 'b'), (2, 'c')] # it return array of tuple so - + output: [(0, 'a'), (1, 'b'), (2, 'c')] # it return array of tuple so + for tup in enumerate(iterable): print(tup) diff --git a/0x_iterators/00_enumerate/01_enum_with_strings.py b/0x_iterators/00_enumerate/01_enum_with_strings.py index 2559d78..9e43bb5 100644 --- a/0x_iterators/00_enumerate/01_enum_with_strings.py +++ b/0x_iterators/00_enumerate/01_enum_with_strings.py @@ -9,4 +9,4 @@ i=2, ch='d' i=3, ch='a' i=4, ch='r' -""" \ No newline at end of file +""" diff --git a/0x_iterators/00_enumerate/02_enum_with_tuples.py b/0x_iterators/00_enumerate/02_enum_with_tuples.py index 6c95a98..441c3c0 100644 --- a/0x_iterators/00_enumerate/02_enum_with_tuples.py +++ b/0x_iterators/00_enumerate/02_enum_with_tuples.py @@ -6,4 +6,4 @@ # Output: # 0 10 # 1 20 -# 2 30 \ No newline at end of file +# 2 30 diff --git a/0x_iterators/00_enumerate/03_enum_with_dic.py b/0x_iterators/00_enumerate/03_enum_with_dic.py index 5eef0ae..9802543 100644 --- a/0x_iterators/00_enumerate/03_enum_with_dic.py +++ b/0x_iterators/00_enumerate/03_enum_with_dic.py @@ -1,8 +1,4 @@ -data = { - "a": 100, - "b": 200, - "c": 300 -} +data = {"a": 100, "b": 200, "c": 300} for index, key in enumerate(data): print(index, key) @@ -12,7 +8,7 @@ # 1 b # 2 c -print(f"{"Index":<10} | {"Key":<10} | {"Value"}") +print(f"{'Index':<10} | {'Key':<10} | {'Value'}") for i, (k, v) in enumerate(data.items()): print(f"{i:<10} | {k:<10} | {v}") @@ -21,4 +17,4 @@ 0 | a | 100 1 | b | 200 2 | c | 300 -""" \ No newline at end of file +""" diff --git a/0x_iterators/00_enumerate/04_enum_with_file.py b/0x_iterators/00_enumerate/04_enum_with_file.py index 883c3b3..49c76b5 100644 --- a/0x_iterators/00_enumerate/04_enum_with_file.py +++ b/0x_iterators/00_enumerate/04_enum_with_file.py @@ -2,6 +2,6 @@ if not f: print("Unable to read file") else: - print(f"{"Line No.":<10} | Contents") + print(f"{'Line No.':<10} | Contents") for line_no, line_contents in enumerate(f, start=1): print(f"{line_no:<10} | {line_contents}") diff --git a/0x_iterators/00_enumerate/04_enum_with_list.py b/0x_iterators/00_enumerate/04_enum_with_list.py index 63e35ff..34c1a51 100644 --- a/0x_iterators/00_enumerate/04_enum_with_list.py +++ b/0x_iterators/00_enumerate/04_enum_with_list.py @@ -19,4 +19,4 @@ -5 apple -4 banana -3 carrot -""" \ No newline at end of file +""" diff --git a/0x_iterators/00_enumerate/05_enum_iterator.py b/0x_iterators/00_enumerate/05_enum_iterator.py index 81768dd..58fc96a 100644 --- a/0x_iterators/00_enumerate/05_enum_iterator.py +++ b/0x_iterators/00_enumerate/05_enum_iterator.py @@ -13,4 +13,4 @@ (2, 'c') """ -# print(next(e)) # Error: raises StopIteration \ No newline at end of file +# print(next(e)) # Error: raises StopIteration diff --git a/0x_iterators/00_enumerate/06_consumed_iterator_behavior.py b/0x_iterators/00_enumerate/06_consumed_iterator_behavior.py index 970739f..54984c2 100644 --- a/0x_iterators/00_enumerate/06_consumed_iterator_behavior.py +++ b/0x_iterators/00_enumerate/06_consumed_iterator_behavior.py @@ -3,5 +3,5 @@ e = enumerate(["a", "b", "c"]) -print(list(e)) # output: [(0, 'a'), (1, 'b'), (2, 'c')] -print(list(e)) # []: Because the iterator is already exhausted. \ No newline at end of file +print(list(e)) # output: [(0, 'a'), (1, 'b'), (2, 'c')] +print(list(e)) # []: Because the iterator is already exhausted. diff --git a/0x_iterators/00_enumerate/07_enum_with_generators.py b/0x_iterators/00_enumerate/07_enum_with_generators.py index 4444989..2aa53f5 100644 --- a/0x_iterators/00_enumerate/07_enum_with_generators.py +++ b/0x_iterators/00_enumerate/07_enum_with_generators.py @@ -2,9 +2,11 @@ # They are useful when working with large datasets, streams of data, or sequences that could be infinite. + def square(): for i in range(5): - yield i*i + yield i * i + for idx, value in enumerate(square()): print(idx, value) @@ -17,4 +19,4 @@ def square(): 4 16 """ -# No extra memory is used to store all values. \ No newline at end of file +# No extra memory is used to store all values. diff --git a/0x_iterators/05_itertools/permutation.ipynb b/0x_iterators/05_itertools/permutation.ipynb index fd56cb8..6a0b010 100644 --- a/0x_iterators/05_itertools/permutation.ipynb +++ b/0x_iterators/05_itertools/permutation.ipynb @@ -68,7 +68,7 @@ "source": [ "from itertools import permutations\n", "\n", - "short_perms = list(permutations(['a', 'b', 'c'], 2))\n", + "short_perms = list(permutations([\"a\", \"b\", \"c\"], 2))\n", "\n", "print(short_perms)" ] @@ -108,7 +108,7 @@ "source": [ "from itertools import permutations\n", "\n", - "word_perms = [''.join(p) for p in permutations('xyz')]\n", + "word_perms = [\"\".join(p) for p in permutations(\"xyz\")]\n", "\n", "print(word_perms)" ] diff --git a/0x_oop/00_class.py b/0x_oop/00_class.py index 0d07730..cf98bbc 100644 --- a/0x_oop/00_class.py +++ b/0x_oop/00_class.py @@ -3,12 +3,13 @@ class Student: def __init__(self): pass -# Method 1: using class name directly -print(Student.__name__) # Output: Student + +# Method 1: using class name directly +print(Student.__name__) # Output: Student # Method 2: Using object/instance std = Student() -print(std.__class__.__name__) # Output: Student +print(std.__class__.__name__) # Output: Student # Method 3: using type -print(type(std).__name__) # Output: Student \ No newline at end of file +print(type(std).__name__) # Output: Student diff --git a/0x_oop/00_dunders_methods/01__dict__.ipynb b/0x_oop/00_dunders_methods/01__dict__.ipynb index 6034cfb..8ee5556 100644 --- a/0x_oop/00_dunders_methods/01__dict__.ipynb +++ b/0x_oop/00_dunders_methods/01__dict__.ipynb @@ -33,10 +33,11 @@ " def bark(self):\n", " print(\"woof\")\n", "\n", + "\n", "d1 = Dog()\n", "d2 = Dog()\n", "\n", - "# Dog.__dict__ is main class dictionary \n", + "# Dog.__dict__ is main class dictionary\n", "print(f\"{Dog.__dict__=}\")\n", "\n", "# d1.__dict__: dictionary {} belongs to d1 only and d2 has its separate. If we define attributes then each instance will have its own arbitrary attributes.\n", @@ -143,7 +144,7 @@ "outputs": [], "source": [ "# suppose we add attribute to the class\n", - "Dog.species = \"Canine\" # here, species belong to the class not instances. But, both can access it and Python will resolve by first looking at instances and then Class." + "Dog.species = \"Canine\" # here, species belong to the class not instances. But, both can access it and Python will resolve by first looking at instances and then Class." ] }, { @@ -218,6 +219,7 @@ "class Dog:\n", " species = \"Canine\"\n", "\n", + "\n", "d = Dog()\n", "\n", "print(d.species)" @@ -238,7 +240,7 @@ "metadata": {}, "outputs": [], "source": [ - "# Now let's update species \n", + "# Now let's update species\n", "d.species = \"Wolf\"" ] }, diff --git a/0x_oop/00_dunders_methods/02__init__.ipynb b/0x_oop/00_dunders_methods/02__init__.ipynb index fed917d..8fbf671 100644 --- a/0x_oop/00_dunders_methods/02__init__.ipynb +++ b/0x_oop/00_dunders_methods/02__init__.ipynb @@ -50,6 +50,7 @@ " def __init__(self, name):\n", " self.name = name # Mutating the __dict__ from inside\n", "\n", + "\n", "d1 = Dog(\"Rex\")" ] }, @@ -64,6 +65,7 @@ "class Dog:\n", " pass\n", "\n", + "\n", "d2 = Dog()\n", "d2.name = \"Rex\" # Mutating the __dict__ from outside" ] diff --git a/0x_oop/00_dunders_methods/03__slots__.ipynb b/0x_oop/00_dunders_methods/03__slots__.ipynb index a763389..e470d3f 100644 --- a/0x_oop/00_dunders_methods/03__slots__.ipynb +++ b/0x_oop/00_dunders_methods/03__slots__.ipynb @@ -75,9 +75,10 @@ "source": [ "# Manual method can be used with tuples __slots__ = (\"name\", \"age\")\n", "\n", + "\n", "class Person:\n", " # Explicitly list allowed attributes as strings\n", - " __slots__ = [\"name\", \"age\"] # list contains attributes of the class\n", + " __slots__ = [\"name\", \"age\"] # list contains attributes of the class\n", "\n", " def __init__(self, name, age):\n", " self.name = name\n", @@ -168,12 +169,14 @@ "source": [ "from dataclasses import dataclass\n", "\n", + "\n", "@dataclass(slots=True)\n", "class Person:\n", " name: str\n", " age: int\n", " height: float\n", "\n", + "\n", "p1 = Person(\"Saqib\", 22, 5.4)" ] }, diff --git a/0x_oop/00_dunders_methods/04__repr__vs__str__.ipynb b/0x_oop/00_dunders_methods/04__repr__vs__str__.ipynb index 7574088..5836f95 100644 --- a/0x_oop/00_dunders_methods/04__repr__vs__str__.ipynb +++ b/0x_oop/00_dunders_methods/04__repr__vs__str__.ipynb @@ -48,12 +48,13 @@ " yield self.name\n", " yield self.dept\n", "\n", + "\n", "import uuid\n", "\n", "s1 = Student(str(uuid.uuid4()), \"Saqib Bedar\", \"CS\")\n", "\n", "# print s1 and see the output, without __repr__ Python will output a cryptic memory address <__main__.Student object at 0x000002CBDA8B56A0>\n", - "print(s1) # Output: <__main__.Student object at 0x000002CBDA8B56A0>" + "print(s1) # Output: <__main__.Student object at 0x000002CBDA8B56A0>" ] }, { @@ -95,6 +96,7 @@ " yield self.name\n", " yield self.dept\n", "\n", + "\n", "import uuid\n", "\n", "# create an object\n", @@ -156,6 +158,7 @@ " def __str__(self):\n", " return f\"'{self.title}' by {self.author}\"\n", "\n", + "\n", "# Create a new book (instance of a book)\n", "my_book = Book(\"Fluent Python\", \"Saqib Bedar\")\n", "\n", @@ -229,10 +232,11 @@ " def __str__(self):\n", " return f\"'{self.title}' by {self.author}\"\n", "\n", - " # priority: 2 (or fallback) \n", + " # priority: 2 (or fallback)\n", " def __repr__(self):\n", " return f\"Book('{self.title!r}, {self.author!r}')\"\n", "\n", + "\n", "my_book = Book(\"Fluent Python\", \"Saqib Bedar\")\n", "\n", "# This triggers __str__\n", diff --git a/0x_oop/01_fundamentals.ipynb b/0x_oop/01_fundamentals.ipynb index 62bffcd..4e2f395 100644 --- a/0x_oop/01_fundamentals.ipynb +++ b/0x_oop/01_fundamentals.ipynb @@ -115,7 +115,7 @@ ], "source": [ "# setter\n", - "p2 = p1 # p2 has now the same object and both p1 and p2 are pointing at it.\n", + "p2 = p1 # p2 has now the same object and both p1 and p2 are pointing at it.\n", "\n", "print(f\"{p1=}\\n{p2=}\\n\")\n", "print(f\"Is same Address? {p1 is p2}\\nAre both equal? {p1 == p2}\")\n", @@ -186,8 +186,8 @@ ], "source": [ "# formatting heading\n", - "print(f\"{\"Index\":<10} | {\"Key\":<10} | {\"Value\":<10}\")\n", - "print(\"-\"*34)\n", + "print(f\"{'Index':<10} | {'Key':<10} | {'Value':<10}\")\n", + "print(\"-\" * 34)\n", "\n", "for i, (k, v) in enumerate(p1.__dict__.items()):\n", " print(f\"{i:<10} | {k:<10} | {v:<10}\")" @@ -235,6 +235,7 @@ "import random\n", "from dataclasses import dataclass\n", "\n", + "\n", "@dataclass\n", "class Student:\n", " # constructor\n", @@ -254,6 +255,7 @@ " self.name = name if name is not None else self.name\n", " self.dept = dept if dept is not None else self.dept\n", "\n", + "\n", "std = [Student(i, f\"STD-{i}\", random.choice([\"AI\", \"CS\", \"DS\", \"SE\", \"IT\"])) for i in range(1, 6)]\n", "\n", "print(std[0])" @@ -329,6 +331,7 @@ " # A set removes duplicates; if sizes match, all elements are unique\n", " return len(std_lst) != len(set(ids))\n", "\n", + "\n", "# check duplicate id\n", "if has_duplicate_ids(std):\n", " print(\"Warning: Duplicate student IDs found!\")\n", diff --git a/0x_oop/01_inheritance/01_inheritance.ipynb b/0x_oop/01_inheritance/01_inheritance.ipynb index 630e48d..44b6e5b 100644 --- a/0x_oop/01_inheritance/01_inheritance.ipynb +++ b/0x_oop/01_inheritance/01_inheritance.ipynb @@ -1,439 +1,461 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "eeea7f74", - "metadata": {}, - "source": [ - "# 1. Inheritance \n", - "\n", - "It allows child class to adopt or inherit attributes and methods from an existing parent class. It promotes reusability." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "b39b3998", - "metadata": {}, - "outputs": [], - "source": [ - "class Student:\n", - " def __init__(self, id, name, department):\n", - " self.id = id\n", - " self.name = name\n", - " self.department = department\n", - "\n", - " # generator\n", - " def get_std(self):\n", - " yield self.id\n", - " yield self.name\n", - " yield self.department\n", - " \n", - " # setter\n", - " # def set_std(self, id, name, department):\n", - " # if self.id != id:\n", - " # self.id = id\n", - " # if self.name != name:\n", - " # self.name = name\n", - " # if self.department != department:\n", - " # self.department = department\n", - "\n", - " # Other way of writing set_std(self)\n", - " # def set_st(self, id=None, name=None, department=None):\n", - " # self.id = id or self.id\n", - " # self.name = name or self.name\n", - " # self.department = department or self.department\n", - "\n", - " # Even better as or operator is ambiguous with falsy values\n", - " def set_std(self, id=None, name=None, department=None):\n", - " self.id = id if id is not None else self.id\n", - " self.name = name if name is not None else self.name\n", - " self.department = department if department is not None else department\n", - "\n", - "\n", - "# random\n", - "import random\n", - "\n", - "# create five random std\n", - "std = [Student(id, f\"Std-{id}\", random.choice([\"CS\", \"AI\", \"DS\", \"SE\", \"IT\"])) for id in range(1, 6)]" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "6fac4ff8", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'id': 1, 'name': 'Std-1', 'department': 'CS'}\n" - ] - } - ], - "source": [ - "print(std[0].__dict__)" - ] - }, - { - "cell_type": "markdown", - "id": "a3911f64", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "9b7db389", - "metadata": {}, - "source": [ - "# Basic Syntax\n", - "\n", - "To inherit from another class, pass the parent class name inside parentheses when defining the child class.\n", - "\n", - "### Example\n", - "\n", - "```py\n", - "# Parent Class\n", - "class Vehicle:\n", - " def __init__(self, brand):\n", - " self.brand = brand\n", - " \n", - " def move(self):\n", - " return \"Moving forward\"\n", - "\n", - "# Child class inherits from Parent class Vehicle\n", - "class Car(Vehicle):\n", - " def honk(self):\n", - " return \"Beep beep!\"\n", - "\n", - "my_car = Car(\"Toyota\")\n", - "\n", - "print(my_car.move()) # Output: Moving forward (Inherited)\n", - "print(my_car.honk()) # Output: Beep beep! (Child specific)\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "id": "54eba65d", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "8e3a20b2", - "metadata": {}, - "source": [ - "# The `super()` Function\n", - "\n", - "The `super()` function allows a child class to call methods from its parent class. This is most frequently used within the `__ init __()` constructor to cleanly initialize parent attributes without duplicating initialization logic." - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "12a94575", - "metadata": {}, - "outputs": [], - "source": [ - "class Employee:\n", - " def __init__(self, name, salary):\n", - " self.name = name\n", - " self.salary = salary\n", - "\n", - "class Developer(Employee):\n", - " def __init__(self, name, salary, programming_lang):\n", - " # Initializes name and salary using the Employee parent constructor\n", - " super().__init__(name, salary) \n", - " self.programming_lang = programming_lang" - ] - }, - { - "cell_type": "markdown", - "id": "cf88d277", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "62e675dd", - "metadata": {}, - "source": [ - "# Method Overriding\n", - "\n", - "If a child class defines a method with the exact same name as a method in its parent class, the child's implementation overrides the parent's. Python will prioritize executing the child's version of that method." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "f731ee66", - "metadata": {}, - "outputs": [], - "source": [ - "class Animal:\n", - " def make_sound(self):\n", - " return \"Generic animal sound\"\n", - "\n", - "class Dog(Animal):\n", - " def make_sound(self):\n", - " return \"Woof!\" # Overrides the parent method" - ] - }, - { - "cell_type": "markdown", - "id": "1cd5eaf1", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "1363b341", - "metadata": {}, - "source": [ - "# Perfect Class Inheritance Example" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bf8f8f55", - "metadata": {}, - "outputs": [], - "source": [ - "class Student:\n", - " def __init__(self, id, name, department):\n", - " self.id = id\n", - " self.name = name\n", - " self.department = department\n", - "\n", - " # generator\n", - " def get_std(self):\n", - " yield self.id\n", - " yield self.name\n", - " yield self.department\n", - "\n", - " # Even better as or operator is ambiguous with falsy values\n", - " def set_std(self, id=None, name=None, department=None):\n", - " self.id = id if id is not None else self.id\n", - " self.name = name if name is not None else self.name\n", - " self.department = department if department is not None else self.department" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "eb2f52cf", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Graduate Student: ('abd7c07e-57f1-4571-98d5-c8b59a488864', 'Alice Vance', 'Neural Networks', 'Dr. Smith', 'Deep Learning')\n" - ] - } - ], - "source": [ - "class GraduateStudent(Student):\n", - " # first initialize all parent attributes\n", - " # Student attributes: id, name, department\n", - " # this attributes: thesis, faculty_advisor, research_area\n", - " def __init__(self, id, name, department, thesis, faculty_advisor, research_area):\n", - " # 1. Initialize parent attributes using super()\n", - " super().__init__(id, name, department)\n", - "\n", - " # 2. Initialize child-specific attributes\n", - " self.thesis = thesis\n", - " self.faculty_advisor = faculty_advisor\n", - " self.research_area = research_area\n", - "\n", - " # 1. Method Overriding: Extending the generator for GraduateStudent\n", - " def get_std(self):\n", - " # Yield parent attributes first\n", - " yield from super().get_std()\n", - "\n", - " # yield child attributes\n", - " yield self.thesis\n", - " yield self.faculty_advisor\n", - " yield self.research_area\n", - "\n", - " # 2. Method Overriding for the setter\n", - " def set_std(self, id=None, name=None, department=None, thesis=None, faculty_advisor=None, research_area=None):\n", - " # 1. Call parent setter to handle id, name, and department\n", - " super().set_std(id, name, department)\n", - "\n", - " # 2. Handle child-specific attributes using same logic (if-else statement expression)\n", - " self.thesis = thesis if thesis is not None else self.thesis\n", - " self.faculty_advisor = faculty_advisor if faculty_advisor is not None else self.faculty_advisor\n", - " self.research_area = research_area if research_area is not None else self.research_area\n", - "\n", - "# Universally Unique Identifiers\n", - "import uuid # for unique id\n", - " \n", - "# Inherited class\n", - "grd_std = GraduateStudent(id=str(uuid.uuid4()), name=\"John Doe\", department=\"CS\", thesis=\"Neural Networks\", faculty_advisor=\"Dr. Smith\", research_area=\"Deep Learning\")\n", - "\n", - "# Use the inherited setter method\n", - "grd_std.set_std(name=\"Alice Vance\")\n", - "\n", - "# unpack generator\n", - "id, name, dept, thesis, fac_adv, rsch_area = grd_std.get_std()\n", - "\n", - "print(f\"Graduate Student: {id, name, thesis, fac_adv, rsch_area}\")" - ] - }, - { - "cell_type": "markdown", - "id": "fe26bf67", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "a398bc24", - "metadata": {}, - "source": [ - "# Types of Inheritance\n", - "\n", - "Python is highly versatile and supports five structural patterns of inheritance:\n", - "\n", - "- **Single**: A single child class inherits from one parent class.\n", - "\n", - "- **Multiple**: A child class inherits directly from more than one parent class.\n", - "\n", - "- **Multilevel**: A child class inherits from a parent, which itself is a child of another class.\n", - "\n", - "- **Hierarchical**: Multiple unique child classes all inherit from the same single parent class.\n", - "\n", - "- **Hybrid**: A combined mixture of two or more of the inheritance types listed above." - ] - }, - { - "cell_type": "markdown", - "id": "70742e41", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "f1a7173d", - "metadata": {}, - "source": [ - "# Method Resolution Order (MRO)\n", - "\n", - "In multiple inheritance scenarios, if different parent classes share identical method names, Python determines which one to execute using the **Method Resolution Order (MRO)**. Python resolves this left-to-right, depth-first, ensuring it does not visit any parent class twice. You can inspect this path by calling `ClassName.mro()` or using the `__ mro __` attribute." - ] - }, - { - "cell_type": "markdown", - "id": "1bfd2173", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "a2a4c62d", - "metadata": {}, - "source": [ - "# Helpful Built-in Functions\n", - "\n", - "- **`isinstance(obj, Class)`**: Returns True if an object is an instance of that class or its subclasses.\n", - "\n", - "- **`issubclass(Child, Parent)`**: Returns True if the first class is a direct or indirect subclass of the second." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "a24d72c2", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[, , ]\n", - "(, , )\n" - ] - } - ], - "source": [ - "print(GraduateStudent.mro()) # return a list\n", - "print(GraduateStudent.__mro__) # return a tuple" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "8aef36aa", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello from B\n", - "[, , , , ]\n" - ] - } - ], - "source": [ - "class A:\n", - " def greet(self):\n", - " return \"Hello from A\"\n", - "\n", - "class B(A):\n", - " def greet(self):\n", - " return \"Hello from B\"\n", - "\n", - "class C(A):\n", - " def greet(self):\n", - " return \"Hello from C\"\n", - "\n", - "class D(B, C):\n", - " pass\n", - "\n", - "obj = D()\n", - "print(obj.greet()) # What will this print?\n", - "print(D.mro())\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.14.4" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} +{ + "cells": [ + { + "cell_type": "markdown", + "id": "eeea7f74", + "metadata": {}, + "source": [ + "# 1. Inheritance \n", + "\n", + "It allows child class to adopt or inherit attributes and methods from an existing parent class. It promotes reusability." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "b39b3998", + "metadata": {}, + "outputs": [], + "source": [ + "class Student:\n", + " def __init__(self, id, name, department):\n", + " self.id = id\n", + " self.name = name\n", + " self.department = department\n", + "\n", + " # generator\n", + " def get_std(self):\n", + " yield self.id\n", + " yield self.name\n", + " yield self.department\n", + "\n", + " # setter\n", + " # def set_std(self, id, name, department):\n", + " # if self.id != id:\n", + " # self.id = id\n", + " # if self.name != name:\n", + " # self.name = name\n", + " # if self.department != department:\n", + " # self.department = department\n", + "\n", + " # Other way of writing set_std(self)\n", + " # def set_st(self, id=None, name=None, department=None):\n", + " # self.id = id or self.id\n", + " # self.name = name or self.name\n", + " # self.department = department or self.department\n", + "\n", + " # Even better as or operator is ambiguous with falsy values\n", + " def set_std(self, id=None, name=None, department=None):\n", + " self.id = id if id is not None else self.id\n", + " self.name = name if name is not None else self.name\n", + " self.department = department if department is not None else department\n", + "\n", + "\n", + "# random\n", + "import random\n", + "\n", + "# create five random std\n", + "std = [Student(id, f\"Std-{id}\", random.choice([\"CS\", \"AI\", \"DS\", \"SE\", \"IT\"])) for id in range(1, 6)]" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "6fac4ff8", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'id': 1, 'name': 'Std-1', 'department': 'CS'}\n" + ] + } + ], + "source": [ + "print(std[0].__dict__)" + ] + }, + { + "cell_type": "markdown", + "id": "a3911f64", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "9b7db389", + "metadata": {}, + "source": [ + "# Basic Syntax\n", + "\n", + "To inherit from another class, pass the parent class name inside parentheses when defining the child class.\n", + "\n", + "### Example\n", + "\n", + "```py\n", + "# Parent Class\n", + "class Vehicle:\n", + " def __init__(self, brand):\n", + " self.brand = brand\n", + " \n", + " def move(self):\n", + " return \"Moving forward\"\n", + "\n", + "# Child class inherits from Parent class Vehicle\n", + "class Car(Vehicle):\n", + " def honk(self):\n", + " return \"Beep beep!\"\n", + "\n", + "my_car = Car(\"Toyota\")\n", + "\n", + "print(my_car.move()) # Output: Moving forward (Inherited)\n", + "print(my_car.honk()) # Output: Beep beep! (Child specific)\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "id": "54eba65d", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "8e3a20b2", + "metadata": {}, + "source": [ + "# The `super()` Function\n", + "\n", + "The `super()` function allows a child class to call methods from its parent class. This is most frequently used within the `__ init __()` constructor to cleanly initialize parent attributes without duplicating initialization logic." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "12a94575", + "metadata": {}, + "outputs": [], + "source": [ + "class Employee:\n", + " def __init__(self, name, salary):\n", + " self.name = name\n", + " self.salary = salary\n", + "\n", + "\n", + "class Developer(Employee):\n", + " def __init__(self, name, salary, programming_lang):\n", + " # Initializes name and salary using the Employee parent constructor\n", + " super().__init__(name, salary)\n", + " self.programming_lang = programming_lang" + ] + }, + { + "cell_type": "markdown", + "id": "cf88d277", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "62e675dd", + "metadata": {}, + "source": [ + "# Method Overriding\n", + "\n", + "If a child class defines a method with the exact same name as a method in its parent class, the child's implementation overrides the parent's. Python will prioritize executing the child's version of that method." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "f731ee66", + "metadata": {}, + "outputs": [], + "source": [ + "class Animal:\n", + " def make_sound(self):\n", + " return \"Generic animal sound\"\n", + "\n", + "\n", + "class Dog(Animal):\n", + " def make_sound(self):\n", + " return \"Woof!\" # Overrides the parent method" + ] + }, + { + "cell_type": "markdown", + "id": "1cd5eaf1", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "1363b341", + "metadata": {}, + "source": [ + "# Perfect Class Inheritance Example" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bf8f8f55", + "metadata": {}, + "outputs": [], + "source": [ + "class Student:\n", + " def __init__(self, id, name, department):\n", + " self.id = id\n", + " self.name = name\n", + " self.department = department\n", + "\n", + " # generator\n", + " def get_std(self):\n", + " yield self.id\n", + " yield self.name\n", + " yield self.department\n", + "\n", + " # Even better as or operator is ambiguous with falsy values\n", + " def set_std(self, id=None, name=None, department=None):\n", + " self.id = id if id is not None else self.id\n", + " self.name = name if name is not None else self.name\n", + " self.department = department if department is not None else self.department" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "eb2f52cf", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Graduate Student: ('abd7c07e-57f1-4571-98d5-c8b59a488864', 'Alice Vance', 'Neural Networks', 'Dr. Smith', 'Deep Learning')\n" + ] + } + ], + "source": [ + "class GraduateStudent(Student):\n", + " # first initialize all parent attributes\n", + " # Student attributes: id, name, department\n", + " # this attributes: thesis, faculty_advisor, research_area\n", + " def __init__(self, id, name, department, thesis, faculty_advisor, research_area):\n", + " # 1. Initialize parent attributes using super()\n", + " super().__init__(id, name, department)\n", + "\n", + " # 2. Initialize child-specific attributes\n", + " self.thesis = thesis\n", + " self.faculty_advisor = faculty_advisor\n", + " self.research_area = research_area\n", + "\n", + " # 1. Method Overriding: Extending the generator for GraduateStudent\n", + " def get_std(self):\n", + " # Yield parent attributes first\n", + " yield from super().get_std()\n", + "\n", + " # yield child attributes\n", + " yield self.thesis\n", + " yield self.faculty_advisor\n", + " yield self.research_area\n", + "\n", + " # 2. Method Overriding for the setter\n", + " def set_std(\n", + " self,\n", + " id=None,\n", + " name=None,\n", + " department=None,\n", + " thesis=None,\n", + " faculty_advisor=None,\n", + " research_area=None,\n", + " ):\n", + " # 1. Call parent setter to handle id, name, and department\n", + " super().set_std(id, name, department)\n", + "\n", + " # 2. Handle child-specific attributes using same logic (if-else statement expression)\n", + " self.thesis = thesis if thesis is not None else self.thesis\n", + " self.faculty_advisor = faculty_advisor if faculty_advisor is not None else self.faculty_advisor\n", + " self.research_area = research_area if research_area is not None else self.research_area\n", + "\n", + "\n", + "# Universally Unique Identifiers\n", + "import uuid # for unique id\n", + "\n", + "# Inherited class\n", + "grd_std = GraduateStudent(\n", + " id=str(uuid.uuid4()),\n", + " name=\"John Doe\",\n", + " department=\"CS\",\n", + " thesis=\"Neural Networks\",\n", + " faculty_advisor=\"Dr. Smith\",\n", + " research_area=\"Deep Learning\",\n", + ")\n", + "\n", + "# Use the inherited setter method\n", + "grd_std.set_std(name=\"Alice Vance\")\n", + "\n", + "# unpack generator\n", + "id, name, dept, thesis, fac_adv, rsch_area = grd_std.get_std()\n", + "\n", + "print(f\"Graduate Student: {id, name, thesis, fac_adv, rsch_area}\")" + ] + }, + { + "cell_type": "markdown", + "id": "fe26bf67", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "a398bc24", + "metadata": {}, + "source": [ + "# Types of Inheritance\n", + "\n", + "Python is highly versatile and supports five structural patterns of inheritance:\n", + "\n", + "- **Single**: A single child class inherits from one parent class.\n", + "\n", + "- **Multiple**: A child class inherits directly from more than one parent class.\n", + "\n", + "- **Multilevel**: A child class inherits from a parent, which itself is a child of another class.\n", + "\n", + "- **Hierarchical**: Multiple unique child classes all inherit from the same single parent class.\n", + "\n", + "- **Hybrid**: A combined mixture of two or more of the inheritance types listed above." + ] + }, + { + "cell_type": "markdown", + "id": "70742e41", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "f1a7173d", + "metadata": {}, + "source": [ + "# Method Resolution Order (MRO)\n", + "\n", + "In multiple inheritance scenarios, if different parent classes share identical method names, Python determines which one to execute using the **Method Resolution Order (MRO)**. Python resolves this left-to-right, depth-first, ensuring it does not visit any parent class twice. You can inspect this path by calling `ClassName.mro()` or using the `__ mro __` attribute." + ] + }, + { + "cell_type": "markdown", + "id": "1bfd2173", + "metadata": {}, + "source": [ + "---" + ] + }, + { + "cell_type": "markdown", + "id": "a2a4c62d", + "metadata": {}, + "source": [ + "# Helpful Built-in Functions\n", + "\n", + "- **`isinstance(obj, Class)`**: Returns True if an object is an instance of that class or its subclasses.\n", + "\n", + "- **`issubclass(Child, Parent)`**: Returns True if the first class is a direct or indirect subclass of the second." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "a24d72c2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[, , ]\n", + "(, , )\n" + ] + } + ], + "source": [ + "print(GraduateStudent.mro()) # return a list\n", + "print(GraduateStudent.__mro__) # return a tuple" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "8aef36aa", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello from B\n", + "[, , , , ]\n" + ] + } + ], + "source": [ + "class A:\n", + " def greet(self):\n", + " return \"Hello from A\"\n", + "\n", + "\n", + "class B(A):\n", + " def greet(self):\n", + " return \"Hello from B\"\n", + "\n", + "\n", + "class C(A):\n", + " def greet(self):\n", + " return \"Hello from C\"\n", + "\n", + "\n", + "class D(B, C):\n", + " pass\n", + "\n", + "\n", + "obj = D()\n", + "print(obj.greet()) # What will this print?\n", + "print(D.mro())" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.14.4" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/0x_oop/02_polymorphism/00_duck_typing.ipynb b/0x_oop/02_polymorphism/00_duck_typing.ipynb index 061ec30..f8b59ef 100644 --- a/0x_oop/02_polymorphism/00_duck_typing.ipynb +++ b/0x_oop/02_polymorphism/00_duck_typing.ipynb @@ -76,6 +76,7 @@ " self.name = name if name is not None else self.name\n", " self.dept = dept if dept is not None else self.dept\n", "\n", + "\n", "# Server Rack Class\n", "class ServerRack:\n", " def __init__(self, rack_id, model, status):\n", @@ -131,7 +132,7 @@ "\n", "# Both work perfectly in the same function\n", "display(s1)\n", - "print(\"-\"*36)\n", + "print(\"-\" * 36)\n", "display(server)" ] }, @@ -207,6 +208,7 @@ " self.name = name if name is not None else self.name\n", " self.dept = dept if dept is not None else self.dept\n", "\n", + "\n", "import uuid\n", "\n", "s1 = Student(str(uuid.uuid4()), \"Saqib Bedar\", \"Computer Science\")\n", @@ -273,6 +275,7 @@ " # Handle error in case if type is different or method is non-existing\n", " print(f\"Error: {type(entity).__name__} does not support standard updates.\")\n", "\n", + "\n", "# Update student1 department\n", "update_dept(entity=s1, new_dept=\"CS\")\n", "\n", @@ -336,28 +339,33 @@ "source": [ "# Disclaimer: AI generated code!\n", "\n", + "\n", "class Duck:\n", " def fly(self):\n", " print(\"Flap flap! The duck is airborne.\")\n", "\n", + "\n", "class Airplane:\n", " def fly(self):\n", " print(\"Vroom! Engines roaring, the plane takes off.\")\n", "\n", + "\n", "class Whale:\n", " def swim(self):\n", " print(\"Splashing through the ocean.\")\n", "\n", + "\n", "# A function that expects ANY object capable of flying\n", "def make_it_fly(flying_object):\n", " flying_object.fly()\n", "\n", + "\n", "# Test cases\n", "duck = Duck()\n", "plane = Airplane()\n", "whale = Whale()\n", "\n", - "make_it_fly(duck) # Works perfectly\n", + "make_it_fly(duck) # Works perfectly\n", "make_it_fly(plane) # Works perfectly! Python does not care that it's a vehicle.\n", "# make_it_fly(whale) # Raises AttributeError: 'Whale' object has no attribute 'fly'" ] diff --git a/0x_oop/patterns/factory_methods/main.py b/0x_oop/patterns/factory_methods/main.py index c0301cc..4684617 100644 --- a/0x_oop/patterns/factory_methods/main.py +++ b/0x_oop/patterns/factory_methods/main.py @@ -1,15 +1,17 @@ from student import Student + # Factory function -def make_student(name: str="", grade: int=0) -> Student: +def make_student(name: str = "", grade: int = 0) -> Student: new_std = Student(name=name, grade=grade) return new_std + # 1. Caching it in a variable std1 = make_student("Saqib Bedar", grade=10) std1.enroll("AI") -print(std1.name) # Output: Saqib Bedar +print(std1.name) # Output: Saqib Bedar # 2. Inline chaining (No variable assignment) std_name = make_student(name="Dur Muhammad").name -print(std_name) # Output: Dur Muhammad \ No newline at end of file +print(std_name) # Output: Dur Muhammad diff --git a/0x_oop/patterns/factory_methods/notes.md b/0x_oop/patterns/factory_methods/notes.md index 041a841..fc77df7 100644 --- a/0x_oop/patterns/factory_methods/notes.md +++ b/0x_oop/patterns/factory_methods/notes.md @@ -8,21 +8,22 @@ def spawn_student(name: str) -> Student: new_student = Student(name=name, grade=10) return new_student # The instance moves out of the function scope + # 2. How to call attributes/methods immediately after the function is over: # Style 1: Catching it in a variable (Cleanest) student_instance = spawn_student("Saqib") print(student_instance.name) # Access attribute -> "Saqib" -student_instance.enroll("AI") # Call method +student_instance.enroll("AI") # Call method # Style 2: Inline Chaining (No variable assignment) # The function executes, returns the object, and you access the attribute instantly. -student_name = spawn_student("Bedar").name -print(student_name) # -> "Bedar" +student_name = spawn_student("Bedar").name +print(student_name) # -> "Bedar" # WARNING: If you chain a method that returns None (like your enroll or upgrade_grade): -result = spawn_student("Saqib").upgrade_grade() -print(result) # -> This prints None! (Because upgrade_grade() modified the object but returned nothing) +result = spawn_student("Saqib").upgrade_grade() +print(result) # -> This prints None! (Because upgrade_grade() modified the object but returned nothing) ``` # Pattern B: Function returns the CLASS BLUEPRINT itself (Metaprogramming) @@ -36,15 +37,16 @@ def get_blueprint(is_premium_student: bool): return Student # Returning the CLASS object, NOT an instance (no parenthesis!) return None + # 2. How to use it when the function call is over: student_class_blueprint = get_blueprint(is_premium_student=True) # Now you use that variable EXACTLY like you would use the original 'Student' keyword to instantiate: my_instance = student_class_blueprint(name="Saqib Bedar", grade=12) -print(my_instance.name) # -> "Saqib Bedar" +print(my_instance.name) # -> "Saqib Bedar" # Inline Chaining Example: # Call function -> gets blueprint -> immediately instantiate with () -> access attribute name = get_blueprint(is_premium_student=True)(name="Direct Call", grade=1).name -print(name) # -> "Direct Call" +print(name) # -> "Direct Call" ``` \ No newline at end of file diff --git a/0x_oop/patterns/factory_methods/student.py b/0x_oop/patterns/factory_methods/student.py index 9404c60..01205cb 100644 --- a/0x_oop/patterns/factory_methods/student.py +++ b/0x_oop/patterns/factory_methods/student.py @@ -8,4 +8,4 @@ def enroll(self, subject: str) -> None: self.subjects.append(subject) def upgrade_grade(self, grade: int) -> None: - self.grade = grade \ No newline at end of file + self.grade = grade diff --git a/0x_oop/patterns/test_patterns/student.py b/0x_oop/patterns/test_patterns/student.py index e28fd16..962a15d 100644 --- a/0x_oop/patterns/test_patterns/student.py +++ b/0x_oop/patterns/test_patterns/student.py @@ -9,4 +9,3 @@ def enroll(self, subject_name: str) -> None: def upgrade_grade(self) -> None: self.grade += 1 - diff --git a/0x_oop/patterns/test_patterns/test_student.py b/0x_oop/patterns/test_patterns/test_student.py index 68b3d94..e33fe77 100644 --- a/0x_oop/patterns/test_patterns/test_student.py +++ b/0x_oop/patterns/test_patterns/test_student.py @@ -1,10 +1,12 @@ from student import Student + # 1. Helper function (factory pattern/factory function) # return new/fresh instance on each function call def make_fresh_student() -> Student: return Student(name="placeholder", grade=10) + # 2. Independent Test Function 1 def test_enrollment(): # Arrange: Call the helper to get an isolated instance @@ -16,6 +18,7 @@ def test_enrollment(): # Assert assert "Machine Learning" in dummy_user_instance.subjects + # 3. Independent Test Function 2 def test_grade_upgrade(): # Arrange: Call the helper again. This instance is 100% separate from the one above! @@ -26,4 +29,4 @@ def test_grade_upgrade(): # Assert assert dummy_user_instance.grade == 11 - assert len(dummy_user_instance.subjects) == 0 # Isolation test: no subject in this instance + assert len(dummy_user_instance.subjects) == 0 # Isolation test: no subject in this instance diff --git a/0x_oop/patterns/test_patterns/test_student_pytest_pattern.py b/0x_oop/patterns/test_patterns/test_student_pytest_pattern.py index 85729b1..5c8c5f1 100644 --- a/0x_oop/patterns/test_patterns/test_student_pytest_pattern.py +++ b/0x_oop/patterns/test_patterns/test_student_pytest_pattern.py @@ -1,13 +1,16 @@ import pytest from student import Student + @pytest.fixture def std() -> Student: """Arrange: Instantiates an independent class body for each test.""" return Student(name="Saqib Bedar", grade=10) + # test cases + # 1. Test enrollment() def test_enrollment(std: Student): std.enroll("Machine Learning") @@ -15,6 +18,7 @@ def test_enrollment(std: Student): assert "Machine Learning" in std.subjects assert len(std.subjects) == 1 + # 2. Test upgrade_grade() def test_upgrade_grade(std: Student): std.upgrade_grade() diff --git a/0x_standalone_topics/0x_execution_model/excution_model.ipynb b/0x_standalone_topics/0x_execution_model/excution_model.ipynb index 51d7ac9..9d1b73f 100644 --- a/0x_standalone_topics/0x_execution_model/excution_model.ipynb +++ b/0x_standalone_topics/0x_execution_model/excution_model.ipynb @@ -76,7 +76,8 @@ } ], "source": [ - "import tokenize, io\n", + "import io\n", + "import tokenize\n", "\n", "code = b\"price = 40\\nqty = 3\\ntotal = price * qty\\nprint(total)\"\n", "\n", @@ -122,7 +123,8 @@ } ], "source": [ - "import tokenize, io\n", + "import io\n", + "import tokenize\n", "\n", "# using blank lines\n", "code = b\"price = 40\\nqty = 3\\n\\ntotal = price * qty\\n\\nprint(total)\"\n", @@ -230,8 +232,8 @@ ], "source": [ "# much formatted\n", - "import tokenize\n", "import io\n", + "import tokenize\n", "\n", "code = b\"price = 40\\nqty = 3\\ntotal = price * qty\\nprint(total)\"\n", "\n", @@ -343,12 +345,14 @@ "# disassembler\n", "import dis\n", "\n", + "\n", "def f():\n", " price = 40\n", " qty = 3\n", " total = price * qty\n", " print(total)\n", "\n", + "\n", "dis.dis(f)" ] }, @@ -385,6 +389,7 @@ ], "source": [ "import dis\n", + "\n", "dis.dis(\"total = price * qty\")" ] }, @@ -478,7 +483,7 @@ "code_string = \"price = 10\\nqty = 20\\ntotal = price * qty\\nprint(total)\"\n", "\n", "# 1. Compile the string into a code object\n", - "compiled_code = compile(code_string, '', 'exec')\n", + "compiled_code = compile(code_string, \"\", \"exec\")\n", "\n", "# 2. Extract the raw bytes, constants, and names\n", "raw_bytes = list(compiled_code.co_code)\n", @@ -494,18 +499,18 @@ "# 3. Step through the byte array 2 bytes at a time (Opcode, Argument)\n", "for i in range(0, len(raw_bytes), 2):\n", " op = raw_bytes[i]\n", - " arg = raw_bytes[i+1]\n", - " \n", + " arg = raw_bytes[i + 1]\n", + "\n", " # Translate the integer op numeric value to its string name\n", " op_name = opcode.opname[op]\n", - " \n", + "\n", " # Contextualize what the argument points to based on the instruction\n", " context = \"\"\n", " if op_name in opcode.hasconst:\n", " context = f\"-> value: {constants[arg]}\"\n", " elif op_name in opcode.hasname:\n", " context = f\"-> variable: '{names[arg]}'\"\n", - " \n", + "\n", " print(f\"Byte Offset {i:02d}: Opcode {op:<3} ({op_name:<12}) | Argument {arg:<3} {context}\")" ] } diff --git a/0x_standalone_topics/0x_memory_model/00_globals_locals.py b/0x_standalone_topics/0x_memory_model/00_globals_locals.py index 36a5113..8015403 100644 --- a/0x_standalone_topics/0x_memory_model/00_globals_locals.py +++ b/0x_standalone_topics/0x_memory_model/00_globals_locals.py @@ -1,10 +1,14 @@ x = "global" + def f(): y = "local" print(locals()) - print(locals() is globals()) # False: because here locals() is tied to function call and its private local namespace, hence, output of print(locals()) is {'y': 'local'} + print( + locals() is globals() + ) # False: because here locals() is tied to function call and its private local namespace, hence, output of print(locals()) is {'y': 'local'} + f() -print(locals() is globals()) # True: because locals() and global() at top level shares same dict. \ No newline at end of file +print(locals() is globals()) # True: because locals() and global() at top level shares same dict. diff --git a/0x_standalone_topics/0x_memory_model/main.ipynb b/0x_standalone_topics/0x_memory_model/main.ipynb index 58bdfba..e473bfb 100644 --- a/0x_standalone_topics/0x_memory_model/main.ipynb +++ b/0x_standalone_topics/0x_memory_model/main.ipynb @@ -90,7 +90,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": null, "id": "a0b49500", "metadata": {}, "outputs": [ @@ -103,8 +103,8 @@ } ], "source": [ - "globals()[\"z\"] = 99 # write a key into the dict by hand...\n", - "print(z)" + "globals()[\"z\"] = 99 # write a key into the dict by hand...\n", + "print(z) # noqa: F821" ] }, { @@ -134,14 +134,16 @@ "source": [ "x = \"I am global\"\n", "\n", + "\n", "def f():\n", " y = \"I am local\"\n", - " print(locals()) # only y — no x here\n", - " print(x) # lookup falls outward to globals()\n", + " print(locals()) # only y — no x here\n", + " print(x) # lookup falls outward to globals()\n", + "\n", "\n", "f()\n", "\n", - "print(locals() is globals()) # True. at module level: one and the same dict" + "print(locals() is globals()) # True. at module level: one and the same dict" ] }, { @@ -172,11 +174,12 @@ " def bark(self):\n", " print(\"woof\")\n", "\n", + "\n", "d = Dog()\n", "d.name = \"Rex\"\n", "\n", - "print(d.__dict__) # instance data only \n", - "print(Dog.__dict__) # the method lives ONCE, on the class" + "print(d.__dict__) # instance data only\n", + "print(Dog.__dict__) # the method lives ONCE, on the class" ] }, { @@ -205,7 +208,7 @@ "x = 10\n", "b = 10\n", "\n", - "print(id(x) == id(b)) # True because 10 is object and x, b are referencing it." + "print(id(x) == id(b)) # True because 10 is object and x, b are referencing it." ] } ], diff --git a/0x_standalone_topics/0x_memory_model/scopes/00_locals.py b/0x_standalone_topics/0x_memory_model/scopes/00_locals.py index cacddd5..b2be70f 100644 --- a/0x_standalone_topics/0x_memory_model/scopes/00_locals.py +++ b/0x_standalone_topics/0x_memory_model/scopes/00_locals.py @@ -1,7 +1,11 @@ # Local (L): variables defined inside current function + def f(): - x = "local" # local scope + x = "local" # local scope + return x + def E(): - x = "local" # local scope \ No newline at end of file + x = "local" # local scope + return x diff --git a/0x_standalone_topics/0x_memory_model/scopes/01_enclosing.py b/0x_standalone_topics/0x_memory_model/scopes/01_enclosing.py index 5216633..6b50037 100644 --- a/0x_standalone_topics/0x_memory_model/scopes/01_enclosing.py +++ b/0x_standalone_topics/0x_memory_model/scopes/01_enclosing.py @@ -1,10 +1,13 @@ # Enclosing (E): It occurs in when writing functions or more specifically in closures. When inner function uses outer function's variables hence those variables scope is called enclosed. + def outer(): x = "outer" + def inner(): print(x) inner() -print(outer()) \ No newline at end of file + +print(outer()) diff --git a/0x_standalone_topics/0x_memory_model/scopes/02_globals.py b/0x_standalone_topics/0x_memory_model/scopes/02_globals.py index 1813c2f..77a14d8 100644 --- a/0x_standalone_topics/0x_memory_model/scopes/02_globals.py +++ b/0x_standalone_topics/0x_memory_model/scopes/02_globals.py @@ -1,4 +1,4 @@ # Globals (G): These are module level. x = 10 -print(globals()) \ No newline at end of file +print(globals()) diff --git a/0x_standalone_topics/0x_memory_model/scopes/03_builtin.py b/0x_standalone_topics/0x_memory_model/scopes/03_builtin.py index 582e248..4ac91ea 100644 --- a/0x_standalone_topics/0x_memory_model/scopes/03_builtin.py +++ b/0x_standalone_topics/0x_memory_model/scopes/03_builtin.py @@ -6,4 +6,4 @@ """ ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'PythonFinalizationError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_IncompleteInputError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] -""" \ No newline at end of file +""" diff --git a/0x_standalone_topics/0x_or_operator/main.ipynb b/0x_standalone_topics/0x_or_operator/main.ipynb index 50d19bb..3ecfabf 100644 --- a/0x_standalone_topics/0x_or_operator/main.ipynb +++ b/0x_standalone_topics/0x_or_operator/main.ipynb @@ -42,13 +42,14 @@ " self.id = id\n", " self.name = name\n", " self.dep = dep\n", - " \n", + "\n", " # The following code with or is dangerous, we will see below how it's gonna cause issues while argument passing\n", " def update(self, id=None, name=None, dep=None):\n", " self.id = id or self.id\n", " self.name = name or self.name\n", " self.dep = dep or self.dep\n", "\n", + "\n", "p1 = Student(5, \"John Doe\", \"Computer Science\")\n", "\n", "print(p1.__dict__)" @@ -145,13 +146,14 @@ " self.id = id\n", " self.name = name\n", " self.dep = dep\n", - " \n", + "\n", " # The following code with or is dangerous, we will see below how it's gonna cause issues while argument passing\n", " def update(self, id=None, name=None, dep=None):\n", " self.id = id if id is not None else self.id\n", " self.name = name if name is not None else self.name\n", " self.dep = dep if dep is not None else dep\n", "\n", + "\n", "p1 = Student(5, \"John Doe\", \"CS\")\n", "print(p1.__dict__)" ] diff --git a/0x_standalone_topics/0x_output_formators/00_str_format.py b/0x_standalone_topics/0x_output_formators/00_str_format.py index 0d4dc71..ea22b5e 100644 --- a/0x_standalone_topics/0x_output_formators/00_str_format.py +++ b/0x_standalone_topics/0x_output_formators/00_str_format.py @@ -1,42 +1,27 @@ # 1. multiplication method -print( - f"{"=" * 12}" - f"Your message" - f"{"=" * 12}" -) +print(f"{'=' * 12}Your message{'=' * 12}") # Output: ============Your Message============ # 2. center(width, fillchar): more readable approach -print("Your Message".center(36, "=")) # Output: ============Your Message============ -print("Your Message".center(36, "-")) # Output: ------------Your Message------------ -print("Your Message".center(36, "*")) # Output: ************Your Message************ -print("Your Message".center(36, "#")) # Output: ############Your Message############ +print("Your Message".center(36, "=")) # Output: ============Your Message============ +print("Your Message".center(36, "-")) # Output: ------------Your Message------------ +print("Your Message".center(36, "*")) # Output: ************Your Message************ +print("Your Message".center(36, "#")) # Output: ############Your Message############ - -# 3. Working with variables and spaces +# 3. Working with variables and spaces index = 0 label = "Cat" pred = "Cat" conf = 0.8 -print( - f"Image {index + 1}: " - f"True = {label:12s} | " - f"Predicted = {pred:12s} | " - f"Confidence = {conf:.4f}" -) +print(f"Image {index + 1}: True = {label:12s} | Predicted = {pred:12s} | Confidence = {conf:.4f}") -print( - f"Image {index + 1}: " - f"True = {label:12s} | " - f"Predicted = {pred:12s} | " - f"Confidence = {conf:.4f}" -) +print(f"Image {index + 1}: True = {label:12s} | Predicted = {pred:12s} | Confidence = {conf:.4f}") """ Image 1: True = Cat | Predicted = Cat | Confidence = 0.8000 Image 1: True = Cat | Predicted = Cat | Confidence = 0.8000 -""" \ No newline at end of file +""" diff --git a/0x_standalone_topics/0x_output_formators/01_str_alignment.py b/0x_standalone_topics/0x_output_formators/01_str_alignment.py index 400cdd6..a63f570 100644 --- a/0x_standalone_topics/0x_output_formators/01_str_alignment.py +++ b/0x_standalone_topics/0x_output_formators/01_str_alignment.py @@ -1,9 +1,9 @@ name = "Ali" -print(f"{name:10}") # Left-aligned in width 10 -print(f"{name:<10}") # Explicit left align -print(f"{name:>10}") # Right align -print(f"{name:^10}") # Center align +print(f"{name:10}") # Left-aligned in width 10 +print(f"{name:<10}") # Explicit left align +print(f"{name:>10}") # Right align +print(f"{name:^10}") # Center align """ Ali @@ -12,6 +12,6 @@ Ali """ -print(f"{name:*<10}") # Ali******* -print(f"{name:*>10}") # *******Ali -print(f"{name:=^10}") # ===Ali==== \ No newline at end of file +print(f"{name:*<10}") # Ali******* +print(f"{name:*>10}") # *******Ali +print(f"{name:=^10}") # ===Ali==== diff --git a/0x_standalone_topics/0x_output_formators/02_integers.py b/0x_standalone_topics/0x_output_formators/02_integers.py index 5d9e936..a48257d 100644 --- a/0x_standalone_topics/0x_output_formators/02_integers.py +++ b/0x_standalone_topics/0x_output_formators/02_integers.py @@ -1,13 +1,13 @@ n = 42 -# n:5 define no. of spaces -print(f"{n:5}") # Output: 42 -print(f"{n:05}") # Output: 00042 zero-padded -print(f"{n:+5}") # Output: +42 Always show plus sign -print(f"{n:+5}") # Output: +42 Always show plus sign +# n:5 define no. of spaces +print(f"{n:5}") # Output: 42 +print(f"{n:05}") # Output: 00042 zero-padded +print(f"{n:+5}") # Output: +42 Always show plus sign +print(f"{n:+5}") # Output: +42 Always show plus sign -n= 1000000 -print(f"{n:,}") # Output: 1,000,000 thousands separator -print(f"{n:_}") # Output: 1_000_000 thousands separator +n = 1000000 +print(f"{n:,}") # Output: 1,000,000 thousands separator +print(f"{n:_}") # Output: 1_000_000 thousands separator -print(f"{-42:+}") # Output: -42 \ No newline at end of file +print(f"{-42:+}") # Output: -42 diff --git a/0x_standalone_topics/0x_output_formators/03_floating.py b/0x_standalone_topics/0x_output_formators/03_floating.py index 277111b..6dab4fd 100644 --- a/0x_standalone_topics/0x_output_formators/03_floating.py +++ b/0x_standalone_topics/0x_output_formators/03_floating.py @@ -1,5 +1,5 @@ e = 2.71828 -print(f"{e:.2f}") # Output: 2.72 -- two decimal places -print(f"{e:.4f}") # Output: 2.7183 -- four decimal places -print(f"{e:10.2f}") # Output: 2.72 -- width 10, 2 decimals \ No newline at end of file +print(f"{e:.2f}") # Output: 2.72 -- two decimal places +print(f"{e:.4f}") # Output: 2.7183 -- four decimal places +print(f"{e:10.2f}") # Output: 2.72 -- width 10, 2 decimals diff --git a/0x_standalone_topics/0x_output_formators/04_percentage.py b/0x_standalone_topics/0x_output_formators/04_percentage.py index 5891cbb..b3d8d90 100644 --- a/0x_standalone_topics/0x_output_formators/04_percentage.py +++ b/0x_standalone_topics/0x_output_formators/04_percentage.py @@ -1,3 +1,3 @@ rate = 0.853 -print(f"{rate:.1%}") # output: 85.3% \ No newline at end of file +print(f"{rate:.1%}") # output: 85.3% diff --git a/0x_standalone_topics/0x_output_formators/05_bin_oct_hex.py b/0x_standalone_topics/0x_output_formators/05_bin_oct_hex.py index 68c1ff1..6d6ec06 100644 --- a/0x_standalone_topics/0x_output_formators/05_bin_oct_hex.py +++ b/0x_standalone_topics/0x_output_formators/05_bin_oct_hex.py @@ -1,6 +1,6 @@ n = 178910 -print(f"{n:b}") # Output: 101011101011011110 -- binary -print(f"{n:o}") # Output: 535336 -- octal -print(f"{n:x}") # Output: 2bade -- hexa lowercase -print(f"{n:X}") # Output: 2BADE -- hexa Uppercase \ No newline at end of file +print(f"{n:b}") # Output: 101011101011011110 -- binary +print(f"{n:o}") # Output: 535336 -- octal +print(f"{n:x}") # Output: 2bade -- hexa lowercase +print(f"{n:X}") # Output: 2BADE -- hexa Uppercase diff --git a/0x_standalone_topics/0x_output_formators/06_sci_notation.py b/0x_standalone_topics/0x_output_formators/06_sci_notation.py index 4446359..aade97f 100644 --- a/0x_standalone_topics/0x_output_formators/06_sci_notation.py +++ b/0x_standalone_topics/0x_output_formators/06_sci_notation.py @@ -2,16 +2,16 @@ n = 12345678 -print(f"{n:e}") # 1.234568e+07 1.234568 × 10^7 -print(f"{n:.2e}") # 1.23e+07 1.23 x 10^7 +print(f"{n:e}") # 1.234568e+07 1.234568 × 10^7 +print(f"{n:.2e}") # 1.23e+07 1.23 x 10^7 # common ML examples lr = 1e-3 -print(f"lr = {lr:.0e}") # lr = 1e-03 1 x 10^-3 +print(f"lr = {lr:.0e}") # lr = 1e-03 1 x 10^-3 loss = 2.34567e-7 -print(f"loss = {loss:.3e}") # loss = 2.346e-07 2.346 x 10^-7 +print(f"loss = {loss:.3e}") # loss = 2.346e-07 2.346 x 10^-7 # Global formatter @@ -25,15 +25,15 @@ """ -x = 0.00001234 -print(f"{x:g}") # 1.234e-05 +x = 0.00001234 +print(f"{x:g}") # 1.234e-05 x = 1234.567 -print(f"{x:g}") # 1234.57 +print(f"{x:g}") # 1234.57 # Significant Digits x = 0.000012345678 -print(f"{x:.3g}") # 1.23e-05 # Show 3 or 5 significant digits, not decimal places. -print(f"{x:.5g}") # 1.234e-05 \ No newline at end of file +print(f"{x:.3g}") # 1.23e-05 # Show 3 or 5 significant digits, not decimal places. +print(f"{x:.5g}") # 1.234e-05 diff --git a/0x_standalone_topics/0x_output_formators/07_debug_fmt.py b/0x_standalone_topics/0x_output_formators/07_debug_fmt.py index 7753bf2..4de2213 100644 --- a/0x_standalone_topics/0x_output_formators/07_debug_fmt.py +++ b/0x_standalone_topics/0x_output_formators/07_debug_fmt.py @@ -1,6 +1,6 @@ -# Debugging formatting +# Debugging formatting name = "Bedar" age = 21 -print(f"{name=} | {age=}") # Output: name='Bedar' | age=21 \ No newline at end of file +print(f"{name=} | {age=}") # Output: name='Bedar' | age=21 diff --git a/0x_standalone_topics/0x_output_formators/08_integer_d.py b/0x_standalone_topics/0x_output_formators/08_integer_d.py index 0127c71..94c8efb 100644 --- a/0x_standalone_topics/0x_output_formators/08_integer_d.py +++ b/0x_standalone_topics/0x_output_formators/08_integer_d.py @@ -2,13 +2,13 @@ n = 42 -print(f"{n:d}") # Output: 42 -- Usually you don't need d by itself because Python already knows it's an integer. +print(f"{n:d}") # Output: 42 -- Usually you don't need d by itself because Python already knows it's an integer. n = 7 -f"{n:03d}" # Output: 007 +f"{n:03d}" # Output: 007 """ 0 -> pad with zeros 3 -> total width = 3 d -> decimal integer -""" \ No newline at end of file +""" diff --git a/0x_standalone_topics/0x_output_formators/09_date_fmt.py b/0x_standalone_topics/0x_output_formators/09_date_fmt.py index 54828ed..4b0f522 100644 --- a/0x_standalone_topics/0x_output_formators/09_date_fmt.py +++ b/0x_standalone_topics/0x_output_formators/09_date_fmt.py @@ -2,5 +2,5 @@ now = datetime.now() -print(f"{now:%Y-%m-%d}") # Output: 2026-06-25 -print(f"{now:%H-%M-%S}") # Output: 21-52-01 \ No newline at end of file +print(f"{now:%Y-%m-%d}") # Output: 2026-06-25 +print(f"{now:%H-%M-%S}") # Output: 21-52-01 diff --git a/0x_standalone_topics/0x_output_formators/10_table.py b/0x_standalone_topics/0x_output_formators/10_table.py index fd0a3b5..c62de7a 100644 --- a/0x_standalone_topics/0x_output_formators/10_table.py +++ b/0x_standalone_topics/0x_output_formators/10_table.py @@ -7,4 +7,4 @@ """ Name Score Ali 95 -""" \ No newline at end of file +""" diff --git a/0x_standalone_topics/0x_output_questions/00_cache_local_variables.ipynb b/0x_standalone_topics/0x_output_questions/00_cache_local_variables.ipynb index 89fe3a6..8ddec80 100644 --- a/0x_standalone_topics/0x_output_questions/00_cache_local_variables.ipynb +++ b/0x_standalone_topics/0x_output_questions/00_cache_local_variables.ipynb @@ -27,13 +27,16 @@ "source": [ "# If a variable value is same then python might intern string that means one single str object and ob_refcnt multiple.\n", "\n", + "\n", "def f():\n", " x = \"Hello\"\n", - " return id(x) # return address of object \"Hello\" where x is currently pointing [x------>\"Hello\"]\n", + " return id(x) # return address of object \"Hello\" where x is currently pointing [x------>\"Hello\"]\n", + "\n", "\n", "def g():\n", " x = \"Hello\"\n", - " return id(x) # return address of object \"Hello\" where x is currently pointing [x------>\"Hello\"]\n", + " return id(x) # return address of object \"Hello\" where x is currently pointing [x------>\"Hello\"]\n", + "\n", "\n", "print(f\"{f()=}, {g()=}\")\n", "\n", @@ -58,19 +61,22 @@ } ], "source": [ - "# CPython mini-integer-cache: -5-256. Hence both functions local variables are pointing to single integer object 5. \n", + "# CPython mini-integer-cache: -5-256. Hence both functions local variables are pointing to single integer object 5.\n", + "\n", "\n", "def f():\n", " x = 5\n", - " return id(x) # return address of integer object 5 where x is currently pointing [x------>5]\n", + " return id(x) # return address of integer object 5 where x is currently pointing [x------>5]\n", + "\n", "\n", "def g():\n", " x = 5\n", - " return id(x) # return address of integer object 5 where x is currently pointing [x------>5]\n", + " return id(x) # return address of integer object 5 where x is currently pointing [x------>5]\n", + "\n", "\n", "print(f\"{f()=}, {g()=}\")\n", "\n", - "print(f() is g()) \n", + "print(f() is g())\n", "print(f() == g())" ] }, @@ -136,11 +142,13 @@ "source": [ "def f():\n", " x = 5\n", - " return x # Return the actual cached object\n", + " return x # Return the actual cached object\n", + "\n", "\n", "def g():\n", " x = 5\n", - " return x # Return the actual cached object\n", + " return x # Return the actual cached object\n", + "\n", "\n", "print(f() is g())" ] diff --git a/0x_standalone_topics/0x_top_builtin_modules/0x_garbage_collector/main.ipynb b/0x_standalone_topics/0x_top_builtin_modules/0x_garbage_collector/main.ipynb index c20be7d..475e8cb 100644 --- a/0x_standalone_topics/0x_top_builtin_modules/0x_garbage_collector/main.ipynb +++ b/0x_standalone_topics/0x_top_builtin_modules/0x_garbage_collector/main.ipynb @@ -104,6 +104,7 @@ "source": [ "import gc\n", "\n", + "\n", "class Node:\n", " def __init__(self, name):\n", " self.name = name\n", @@ -114,8 +115,8 @@ "a = Node(\"A\")\n", "b = Node(\"B\")\n", "\n", - "a.link = b # A points B\n", - "b.link = a # B points A" + "a.link = b # A points B\n", + "b.link = a # B points A" ] }, { @@ -193,7 +194,7 @@ "a_refcnt = ctypes.c_long.from_address(address_of_A).value\n", "b_refcnt = ctypes.c_long.from_address(address_of_B).value\n", "\n", - "# refcnt using address before destroying of labels \n", + "# refcnt using address before destroying of labels\n", "print(f\"a_refcnt: {a_refcnt}\")\n", "print(f\"b_refcnt: {b_refcnt}\")" ] @@ -252,7 +253,7 @@ "a_refcnt = ctypes.c_long.from_address(address_of_A).value\n", "b_refcnt = ctypes.c_long.from_address(address_of_B).value\n", "\n", - "# refcnt using address before destroying of labels \n", + "# refcnt using address before destroying of labels\n", "print(f\"a_refcnt: {a_refcnt}\")\n", "print(f\"b_refcnt: {b_refcnt}\")" ] @@ -308,7 +309,7 @@ "secret_cache.append(my_data)\n", "\n", "# Find out what is pointing to my_data\n", - "owners = gc.get_referrers(my_data) # owners(referrers): all labels arrows pointing at my_data\n", + "owners = gc.get_referrers(my_data) # owners(referrers): all labels arrows pointing at my_data\n", "\n", "for owner in owners:\n", " print(type(owner))\n", @@ -357,11 +358,11 @@ "try:\n", " # 2. Run a high-speed, intensive operation\n", " results = [x * 2 for x in range(10_000_000)]\n", - " \n", + "\n", "finally:\n", " # 3. Always re-enable it afterward to prevent long-term leaks\n", " gc.enable()\n", - " gc.collect() # Clean up the leftovers manually" + " gc.collect() # Clean up the leftovers manually" ] }, { @@ -407,12 +408,14 @@ "source": [ "import gc\n", "\n", + "\n", "def print_gc_health():\n", " stats = gc.get_stats()\n", " # Let's inspect Generation 0 (index 0) where new objects land\n", " gen0 = stats[0]\n", " print(f\"Gen 0 -> Sweeps: {gen0['collections']}, Cleared Objects: {gen0['collected']}\")\n", "\n", + "\n", "print(\"--- Initial stats ---\")\n", "print_gc_health()\n", "\n", @@ -475,30 +478,33 @@ "import gc\n", "import weakref\n", "\n", + "\n", "class Parent:\n", " def __init__(self):\n", " # Strong reference: Parent owns Child\n", - " self.child = Child(self) \n", + " self.child = Child(self)\n", + "\n", "\n", "class Child:\n", " def __init__(self, parent_obj):\n", " # WEAK reference: Points to parent without \"owning\" it\n", " self.parent = weakref.ref(parent_obj)\n", "\n", + "\n", "# 1. Create the relationship\n", "mom = Parent()\n", "\n", "# 2. To talk to the parent from the child, you call it like a function:\n", "parent_reference = mom.child.parent()\n", - "print(f\"Child's parent exists: {parent_reference is not None}\") # True\n", + "print(f\"Child's parent exists: {parent_reference is not None}\") # True\n", "\n", "# 3. Delete the parent strong reference\n", - "mom = None \n", + "mom = None\n", "\n", "# 4. Because we used weakref, it drops to 0 count and deletes instantly.\n", "# Let's run a manual check to prove the GC didn't have to clean up a loop:\n", "unreachable = gc.collect()\n", - "print(f\"GC had to destroy {unreachable} cyclic loops.\") # Output will be 0!" + "print(f\"GC had to destroy {unreachable} cyclic loops.\") # Output will be 0!" ] } ], diff --git a/0x_standalone_topics/0x_top_builtin_modules/0x_obj_refcnt/mani.ipynb b/0x_standalone_topics/0x_top_builtin_modules/0x_obj_refcnt/mani.ipynb index c5e7749..719c869 100644 --- a/0x_standalone_topics/0x_top_builtin_modules/0x_obj_refcnt/mani.ipynb +++ b/0x_standalone_topics/0x_top_builtin_modules/0x_obj_refcnt/mani.ipynb @@ -128,7 +128,7 @@ } ], "source": [ - "b = obj_lst # now list object has two ref's, original a and b pointing to it\n", + "b = obj_lst # now list object has two ref's, original a and b pointing to it\n", "\n", "count = ctypes.c_long.from_address(id(obj_lst)).value\n", "\n", @@ -193,8 +193,9 @@ " def get(self):\n", " return self.name\n", "\n", + "\n", "p1 = Person(\"Saqib Bedar\")\n", - "p2 = p1 # now p2 is pointing to class instance object exactly where p1 is pointing currently. (single obj two refcnt)" + "p2 = p1 # now p2 is pointing to class instance object exactly where p1 is pointing currently. (single obj two refcnt)" ] }, { diff --git a/0x_standalone_topics/0x_top_builtin_modules/0x_timeit/main.ipynb b/0x_standalone_topics/0x_top_builtin_modules/0x_timeit/main.ipynb index 624d9b4..50e48a0 100644 --- a/0x_standalone_topics/0x_top_builtin_modules/0x_timeit/main.ipynb +++ b/0x_standalone_topics/0x_top_builtin_modules/0x_timeit/main.ipynb @@ -53,11 +53,7 @@ "\n", "# Code to test is passed to 'stmt'\n", "# Setup operations (like imports) are passed to 'setup'\n", - "execution_time = timeit.timeit(\n", - " stmt=\"[x**2 for x in range(100)]\", \n", - " setup=\"pass\", \n", - " number=100000\n", - ")\n", + "execution_time = timeit.timeit(stmt=\"[x**2 for x in range(100)]\", setup=\"pass\", number=100000)\n", "\n", "print(f\"Total time for 100,000 runs: {execution_time:.4f} seconds\")" ] @@ -87,9 +83,11 @@ "source": [ "import timeit\n", "\n", + "\n", "def test_logic():\n", " return list(map(lambda x: x**2, range(100)))\n", "\n", + "\n", "# Pass the function directly. 'number' defaults to 1,000,000 if omitted.\n", "execution_time = timeit.timeit(test_logic, number=100000)\n", "print(f\"Total time: {execution_time:.4f} seconds\")" diff --git a/0x_standalone_topics/0x_top_builtin_modules/0x_uuid_secrets/uuid.ipynb b/0x_standalone_topics/0x_top_builtin_modules/0x_uuid_secrets/uuid.ipynb index 620e772..1de2d8e 100644 --- a/0x_standalone_topics/0x_top_builtin_modules/0x_uuid_secrets/uuid.ipynb +++ b/0x_standalone_topics/0x_top_builtin_modules/0x_uuid_secrets/uuid.ipynb @@ -50,12 +50,14 @@ "import secrets\n", "import string\n", "\n", + "\n", "def generate_short_id(length=12):\n", " # Alphabet: Letters (upper/lower) + Digits (62 total characters)\n", " alphabet = string.ascii_letters + string.digits\n", - " \n", + "\n", " # Securely choose characters and join them\n", - " return ''.join(secrets.choice(alphabet) for _ in range(length))\n", + " return \"\".join(secrets.choice(alphabet) for _ in range(length))\n", + "\n", "\n", "# Example Usage\n", "print(generate_short_id(12)) # Output: 'J67pSyhIrKgw'" diff --git a/closures/00_first_program.py b/closures/00_first_program.py index eb07f2d..42c2ea2 100644 --- a/closures/00_first_program.py +++ b/closures/00_first_program.py @@ -9,14 +9,16 @@ +----------------+ """ + def outer(): x = 10 def inner(): return x - + return inner + f = outer() print(f()) diff --git a/closures/01_counter.py b/closures/01_counter.py index e568a8f..c4f942d 100644 --- a/closures/01_counter.py +++ b/closures/01_counter.py @@ -1,26 +1,26 @@ def make_counter(): - count = 0 # enclosed variable + count = 0 # enclosed variable def counter(): - nonlocal count # Declares intent to modify outer variable + nonlocal count # Declares intent to modify outer variable count += 1 return count - + return counter my_counter = make_counter() -print(my_counter()) # 1 -print(my_counter()) # 2 +print(my_counter()) # 1 +print(my_counter()) # 2 # Inspecting a Closure # Python stores the captured variables (called "free variables") in a special hidden attribute called __closure__. # Inspecting the 'my_counter' -print(my_counter.__closure__) +print(my_counter.__closure__) # Output: (,) -print(my_counter.__closure__[0].cell_contents) -# Output: 2 \ No newline at end of file +print(my_counter.__closure__[0].cell_contents) +# Output: 2 diff --git a/closures/02_make_multiplier.py b/closures/02_make_multiplier.py index 995494b..7f80c5e 100644 --- a/closures/02_make_multiplier.py +++ b/closures/02_make_multiplier.py @@ -2,12 +2,12 @@ def make_multiplier(factor): # enclosing scope variable: factor def multiplier(number): return number * factor # inner function ref 'factor' - - return multiplier # return inner function + + return multiplier # return inner function double = make_multiplier(2) triple = make_multiplier(3) -print(double(5)) # 10 -print(triple(5)) # 15 \ No newline at end of file +print(double(5)) # 10 +print(triple(5)) # 15 diff --git a/comprehensions/inline-if-else.ipynb b/comprehensions/inline-if-else.ipynb index e15dc9f..e5dec54 100644 --- a/comprehensions/inline-if-else.ipynb +++ b/comprehensions/inline-if-else.ipynb @@ -189,8 +189,8 @@ } ], "source": [ - "user_role = None # can be admin etc\n", - "username = user_role or \"Guest\" # if leftside true assign it else assign default value \n", + "user_role = None # can be admin etc\n", + "username = user_role or \"Guest\" # if leftside true assign it else assign default value\n", "print(username)" ] }, diff --git a/core_libs/matplotlib/matplotlib.ipynb b/core_libs/matplotlib/matplotlib.ipynb index 8f236e7..01657dd 100644 --- a/core_libs/matplotlib/matplotlib.ipynb +++ b/core_libs/matplotlib/matplotlib.ipynb @@ -28,8 +28,8 @@ "# create line plot\n", "plt.plot(x, y, marker=\"o\")\n", "plt.title(\"Line Plot\")\n", - "plt.xlabel('X Axis')\n", - "plt.ylabel('Y Axis')\n", + "plt.xlabel(\"X Axis\")\n", + "plt.ylabel(\"Y Axis\")\n", "plt.show()" ] } diff --git a/core_libs/numpy/01_numpy_broadcasting.ipynb b/core_libs/numpy/01_numpy_broadcasting.ipynb index d9937ef..e3a0c43 100644 --- a/core_libs/numpy/01_numpy_broadcasting.ipynb +++ b/core_libs/numpy/01_numpy_broadcasting.ipynb @@ -50,11 +50,10 @@ "source": [ "import numpy as np\n", "\n", - "matrix = np.array([[1, 2],\n", - " [3, 3]])\n", + "matrix = np.array([[1, 2], [3, 3]])\n", "\n", "# Every single element gets 10 added to it\n", - "print(matrix+10)" + "print(matrix + 10)" ] }, { @@ -91,8 +90,7 @@ } ], "source": [ - "matrix = np.array([[10, 20], \n", - " [30, 40]])\n", + "matrix = np.array([[10, 20], [30, 40]])\n", "\n", "column_bonuses = np.array([1, 2])\n", "# NumPy stretches column_bonuses vertically to become [[1, 2], [1, 2]]\n", @@ -134,17 +132,15 @@ "import numpy as np\n", "\n", "# A 2x2 matrix of original scores\n", - "scores = np.array([80, \n", - " 90])\n", + "scores = np.array([80, 90])\n", "\n", "# A column vector: shape (2, 1)\n", "# Student 0 gets +5 points, Student 1 gets +10 points\n", - "row_bonuses = np.array([[5], \n", - " [10]])\n", + "row_bonuses = np.array([[5], [10]])\n", "\n", "# NumPy stretches row_bonuses horizontally to match the 2x2 shape\n", "# It becomes: [[5, 5],\n", - "#]\n", + "# ]\n", "print(scores + row_bonuses)" ] } diff --git a/core_libs/numpy/interview/01_automatic_name_generator.py b/core_libs/numpy/interview/01_automatic_name_generator.py index 75d684f..d271941 100644 --- a/core_libs/numpy/interview/01_automatic_name_generator.py +++ b/core_libs/numpy/interview/01_automatic_name_generator.py @@ -1,37 +1,41 @@ import numpy as np # 1. Fixed the 'Z' typo in the last row -matrix = np.array([ - ['A', 'B', 'C'], - ['D', 'E', 'F'], - ['G', 'H', 'I'], - ['J', 'K', 'L'], - ['M', 'N', 'O'], - ['P', 'Q', 'R'], - ['S', 'T', 'U'], - ['V', 'W', 'X'], - ['Y', 'Z', ' '] -]) +matrix = np.array( + [ + ["A", "B", "C"], + ["D", "E", "F"], + ["G", "H", "I"], + ["J", "K", "L"], + ["M", "N", "O"], + ["P", "Q", "R"], + ["S", "T", "U"], + ["V", "W", "X"], + ["Y", "Z", " "], + ] +) # Build coordinate lookup dictionary -coord_map = {matrix[r, c]: (r, c) for r, c in np.argwhere(matrix != '')} +coord_map = {matrix[r, c]: (r, c) for r, c in np.argwhere(matrix != "")} + def extract_name(target_name, matrix, coord_map): target_name = target_name.upper() - + try: # 2. SEPARATE row and column coordinates correctly rows = [coord_map[letter][0] for letter in target_name] cols = [coord_map[letter][1] for letter in target_name] except KeyError as e: return f"Error: The letter {e} is not in the matrix." - + # 3. Extract all characters at once using advanced indexing extracted_chars = matrix[rows, cols] - + # 4. Join and return capitalized name return "".join(extracted_chars).title() + # ---- Test Cases ---- print(extract_name("Saqib", matrix, coord_map)) # Output: Saqib -print(extract_name("Dur", matrix, coord_map)) # Output: Dur +print(extract_name("Dur", matrix, coord_map)) # Output: Dur diff --git a/core_libs/numpy/interview/02_boolean_masking.ipynb b/core_libs/numpy/interview/02_boolean_masking.ipynb index baac0e4..93a0322 100644 --- a/core_libs/numpy/interview/02_boolean_masking.ipynb +++ b/core_libs/numpy/interview/02_boolean_masking.ipynb @@ -19,12 +19,7 @@ "source": [ "import numpy as np\n", "\n", - "matrix = np.array([\n", - " [1, 2, 3, 4],\n", - " [5, 6, 7, 8],\n", - " [9, 10, 11, 12],\n", - " [13, 14, 15, 16]\n", - " ])" + "matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])" ] }, { diff --git a/core_libs/numpy/interview/04_challenge_problem.ipynb b/core_libs/numpy/interview/04_challenge_problem.ipynb index 024025d..be08642 100644 --- a/core_libs/numpy/interview/04_challenge_problem.ipynb +++ b/core_libs/numpy/interview/04_challenge_problem.ipynb @@ -82,10 +82,10 @@ "prices = np.array([[10, 2], [8, 1]])\n", "\n", "# STEP A: Use true matrix multiplication (@)\n", - "daily_totals = sales @ prices \n", + "daily_totals = sales @ prices\n", "\n", "# STEP B: Sum rows to get total revenue (Base + Tax) per day\n", - "total_revenue_per_day = daily_totals.sum(axis=1) \n", + "total_revenue_per_day = daily_totals.sum(axis=1)\n", "print(\"Correct Total Revenue per day (Mon, Tue):\", total_revenue_per_day)\n", "# Output: [150 51] (Monday made $150 total, Tuesday made $51)\n", "\n", diff --git a/core_libs/numpy/numpy.ipynb b/core_libs/numpy/numpy.ipynb index a62508e..a871ff0 100644 --- a/core_libs/numpy/numpy.ipynb +++ b/core_libs/numpy/numpy.ipynb @@ -108,7 +108,7 @@ "# 3D\n", "c = np.array([[[1, 2], [3, 4], [5, 6], [7, 8]]])\n", "\n", - "print(f\"{a}\\n{\"-\"*4}\\n{b}\\n{\"-\"*4}\\n{c}\\n\\n\")\n", + "print(f\"{a}\\n{'-' * 4}\\n{b}\\n{'-' * 4}\\n{c}\\n\\n\")\n", "\n", "print(f\"shape of a: {a.shape}\")\n", "print(f\"shape of b: {b.shape}\")\n", @@ -140,7 +140,7 @@ } ], "source": [ - "print(np.zeros((3, 4))) # 3x4 matrix of 0.0" + "print(np.zeros((3, 4))) # 3x4 matrix of 0.0" ] }, { @@ -160,7 +160,7 @@ } ], "source": [ - "print(np.ones((3, 4))) # 2x3 matrix of 1.0" + "print(np.ones((3, 4))) # 2x3 matrix of 1.0" ] }, { @@ -180,7 +180,7 @@ } ], "source": [ - "print(np.full((3,4), fill_value=7)) # 3x3 matrix filled with 7" + "print(np.full((3, 4), fill_value=7)) # 3x3 matrix filled with 7" ] }, { @@ -208,9 +208,9 @@ } ], "source": [ - "print(np.eye(4)) # 4x4 identity matrix (k argument modify diagonal position)\n", + "print(np.eye(4)) # 4x4 identity matrix (k argument modify diagonal position)\n", "\n", - "print(\"\\n\", \"-\"*14, \"\\n\")\n", + "print(\"\\n\", \"-\" * 14, \"\\n\")\n", "\n", "# using k argument to adjust diagonal position\n", "print(np.eye(4, k=1))" @@ -233,7 +233,7 @@ } ], "source": [ - "print(np.identity(3)) # 3x3 identity matrix (no K argument pure identity)" + "print(np.identity(3)) # 3x3 identity matrix (no K argument pure identity)" ] }, { @@ -252,7 +252,7 @@ } ], "source": [ - "print(np.empty((2, 2))) # Uninitialized (fast, garbage values)" + "print(np.empty((2, 2))) # Uninitialized (fast, garbage values)" ] } ], diff --git a/core_libs/numpy/practice/01_intro_to_numpy.ipynb b/core_libs/numpy/practice/01_intro_to_numpy.ipynb index 06e1d76..d2d677e 100644 --- a/core_libs/numpy/practice/01_intro_to_numpy.ipynb +++ b/core_libs/numpy/practice/01_intro_to_numpy.ipynb @@ -94,12 +94,12 @@ "# Type/dimension/shape\n", "\n", "# using python way\n", - "print(f\"Type: {type(array)} || {type(array).__name__}\") # returns class name \n", + "print(f\"Type: {type(array)} || {type(array).__name__}\") # returns class name\n", "\n", "# standard way\n", - "print(f\"Dimensions: {array.ndim}\") # returns int\n", + "print(f\"Dimensions: {array.ndim}\") # returns int\n", "# get the shape\n", - "print(f\"Shape: {array.shape}\") # returns tuple" + "print(f\"Shape: {array.shape}\") # returns tuple" ] }, { diff --git a/core_libs/numpy/practice/02_numpy_ndim_arrays.ipynb b/core_libs/numpy/practice/02_numpy_ndim_arrays.ipynb index 35ab0e7..08f2e95 100644 --- a/core_libs/numpy/practice/02_numpy_ndim_arrays.ipynb +++ b/core_libs/numpy/practice/02_numpy_ndim_arrays.ipynb @@ -46,7 +46,7 @@ ], "source": [ "# 0 dimensional array (Scalar)\n", - "zdim_array = np.array('A')\n", + "zdim_array = np.array(\"A\")\n", "\n", "print(zdim_array)\n", "print(f\"Dimensions: {zdim_array.ndim}\")\n", @@ -71,7 +71,7 @@ ], "source": [ "# 1D array (Vector)\n", - "one_dim_array = np.array(['A', 'B', 'C', 'D'])\n", + "one_dim_array = np.array([\"A\", \"B\", \"C\", \"D\"])\n", "\n", "print(one_dim_array)\n", "print(f\"Dimensions: {one_dim_array.ndim}\")\n", @@ -96,13 +96,17 @@ "# Error expected: read note.\n", "try:\n", " # 2D array (Matrix)\n", - " matrix = np.array([['A', 'B', 'C', 'D'],\n", - " ['E', 'F', 'G', 'H'], \n", - " ['I', 'J', 'K', 'L'], \n", - " ['M', 'N', 'O', 'P'], \n", - " ['Q', 'R', 'S', 'T'],\n", - " ['U', 'V', 'W', 'X'],\n", - " ['Y', 'Z']])\n", + " matrix = np.array(\n", + " [\n", + " [\"A\", \"B\", \"C\", \"D\"],\n", + " [\"E\", \"F\", \"G\", \"H\"],\n", + " [\"I\", \"J\", \"K\", \"L\"],\n", + " [\"M\", \"N\", \"O\", \"P\"],\n", + " [\"Q\", \"R\", \"S\", \"T\"],\n", + " [\"U\", \"V\", \"W\", \"X\"],\n", + " [\"Y\", \"Z\"],\n", + " ]\n", + " )\n", " print(matrix)\n", "except ValueError as e:\n", " print(f\"Error: {e}\")" @@ -137,14 +141,18 @@ ], "source": [ "# 2D array (Matrix)\n", - "matrix = np.array([['A', 'B', 'C', 'D'],\n", - " ['E', 'F', 'G', 'H'], \n", - " ['I', 'J', 'K', 'L'], \n", - " ['M', 'N', 'O', 'P'], \n", - " ['Q', 'R', 'S', 'T'],\n", - " ['U', 'V', 'W', 'X'],\n", - " # Using _ as placeholder values \n", - " ['Y', 'Z', '_', '_']])\n", + "matrix = np.array(\n", + " [\n", + " [\"A\", \"B\", \"C\", \"D\"],\n", + " [\"E\", \"F\", \"G\", \"H\"],\n", + " [\"I\", \"J\", \"K\", \"L\"],\n", + " [\"M\", \"N\", \"O\", \"P\"],\n", + " [\"Q\", \"R\", \"S\", \"T\"],\n", + " [\"U\", \"V\", \"W\", \"X\"],\n", + " # Using _ as placeholder values\n", + " [\"Y\", \"Z\", \"_\", \"_\"],\n", + " ]\n", + ")\n", "\n", "print(f\".ndim: Dimension - {matrix.ndim}\")\n", "print(f\".shape: Shape - {matrix.shape}\")\n", @@ -172,14 +180,16 @@ "source": [ "# Multi-dimensional array (ndim)\n", "# cube\n", - "cube = np.array([\n", - " [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']],\n", - " [['M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T'], ['U', 'V', 'W', 'X']],\n", - " [['Y', 'Z', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_']]\n", - " ])\n", + "cube = np.array(\n", + " [\n", + " [[\"A\", \"B\", \"C\", \"D\"], [\"E\", \"F\", \"G\", \"H\"], [\"I\", \"J\", \"K\", \"L\"]],\n", + " [[\"M\", \"N\", \"O\", \"P\"], [\"Q\", \"R\", \"S\", \"T\"], [\"U\", \"V\", \"W\", \"X\"]],\n", + " [[\"Y\", \"Z\", \"_\", \"_\"], [\"_\", \"_\", \"_\", \"_\"], [\"_\", \"_\", \"_\", \"_\"]],\n", + " ]\n", + ")\n", "\n", "print(f\"Dimension: {cube.ndim}\")\n", - "print(f\"Shape: {cube.shape}\") # for cube: tuple (depth, rows, cols)" + "print(f\"Shape: {cube.shape}\") # for cube: tuple (depth, rows, cols)" ] }, { @@ -200,16 +210,18 @@ "source": [ "# Multi-dimensional array (ndim)\n", "# four dimensional array\n", - "fdim_array = np.array([\n", - " [\n", - " [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']],\n", - " [['M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T'], ['U', 'V', 'W', 'X']]\n", - " ],\n", - " [\n", - " [['M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T'], ['U', 'V', 'W', 'X']],\n", - " [['Y', 'Z', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_']]\n", - " ]\n", - " ])\n", + "fdim_array = np.array(\n", + " [\n", + " [\n", + " [[\"A\", \"B\", \"C\", \"D\"], [\"E\", \"F\", \"G\", \"H\"], [\"I\", \"J\", \"K\", \"L\"]],\n", + " [[\"M\", \"N\", \"O\", \"P\"], [\"Q\", \"R\", \"S\", \"T\"], [\"U\", \"V\", \"W\", \"X\"]],\n", + " ],\n", + " [\n", + " [[\"M\", \"N\", \"O\", \"P\"], [\"Q\", \"R\", \"S\", \"T\"], [\"U\", \"V\", \"W\", \"X\"]],\n", + " [[\"Y\", \"Z\", \"_\", \"_\"], [\"_\", \"_\", \"_\", \"_\"], [\"_\", \"_\", \"_\", \"_\"]],\n", + " ],\n", + " ]\n", + ")\n", "\n", "print(f\"Dimension: {fdim_array.ndim}\")\n", "print(f\"Shape: {fdim_array.shape}\")" diff --git a/core_libs/numpy/practice/03_chain_indexing.ipynb b/core_libs/numpy/practice/03_chain_indexing.ipynb index f9caa73..e86db06 100644 --- a/core_libs/numpy/practice/03_chain_indexing.ipynb +++ b/core_libs/numpy/practice/03_chain_indexing.ipynb @@ -59,9 +59,9 @@ "array = np.array([1, 2, 3, 4])\n", "\n", "# access elements just how you do in Python list\n", - "print(array[0]) # first element at index 0: 1\n", - "print(array[:]) # slicing: full list\n", - "print(array[-1]) # Last element (-1: negative index starts from last)" + "print(array[0]) # first element at index 0: 1\n", + "print(array[:]) # slicing: full list\n", + "print(array[-1]) # Last element (-1: negative index starts from last)" ] }, { @@ -95,15 +95,19 @@ } ], "source": [ - "matrix = np.array([['A', 'B', 'C'], \n", - " ['D', 'E', 'F'], \n", - " ['G', 'H', 'I'], \n", - " ['J', 'K', 'L'], \n", - " ['M', 'N', 'O'], \n", - " ['P', 'Q', 'R'], \n", - " ['S', 'T', 'U'], \n", - " ['V', 'W', 'X'], \n", - " ['Y', 'Y', ' ']])\n", + "matrix = np.array(\n", + " [\n", + " [\"A\", \"B\", \"C\"],\n", + " [\"D\", \"E\", \"F\"],\n", + " [\"G\", \"H\", \"I\"],\n", + " [\"J\", \"K\", \"L\"],\n", + " [\"M\", \"N\", \"O\"],\n", + " [\"P\", \"Q\", \"R\"],\n", + " [\"S\", \"T\", \"U\"],\n", + " [\"V\", \"W\", \"X\"],\n", + " [\"Y\", \"Y\", \" \"],\n", + " ]\n", + ")\n", "\n", "# print your name using subscript operator\n", "# use concatenation\n", @@ -151,11 +155,13 @@ ], "source": [ "# cube\n", - "cube = np.array([\n", - " [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']],\n", - " [['M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T'], ['U', 'V', 'W', 'X']],\n", - " [['Y', 'Z', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_']]\n", - " ])\n", + "cube = np.array(\n", + " [\n", + " [[\"A\", \"B\", \"C\", \"D\"], [\"E\", \"F\", \"G\", \"H\"], [\"I\", \"J\", \"K\", \"L\"]],\n", + " [[\"M\", \"N\", \"O\", \"P\"], [\"Q\", \"R\", \"S\", \"T\"], [\"U\", \"V\", \"W\", \"X\"]],\n", + " [[\"Y\", \"Z\", \"_\", \"_\"], [\"_\", \"_\", \"_\", \"_\"], [\"_\", \"_\", \"_\", \"_\"]],\n", + " ]\n", + ")\n", "\n", "# print z\n", "print(cube[2][0][1])" @@ -193,16 +199,18 @@ ], "source": [ "# four dimensional array\n", - "fdim_array = np.array([\n", - " [\n", - " [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']],\n", - " [['M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T'], ['U', 'V', 'W', 'X']]\n", - " ],\n", - " [\n", - " [['M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T'], ['U', 'V', 'W', 'X']],\n", - " [['Y', 'Z', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_']]\n", - " ]\n", - " ])\n", + "fdim_array = np.array(\n", + " [\n", + " [\n", + " [[\"A\", \"B\", \"C\", \"D\"], [\"E\", \"F\", \"G\", \"H\"], [\"I\", \"J\", \"K\", \"L\"]],\n", + " [[\"M\", \"N\", \"O\", \"P\"], [\"Q\", \"R\", \"S\", \"T\"], [\"U\", \"V\", \"W\", \"X\"]],\n", + " ],\n", + " [\n", + " [[\"M\", \"N\", \"O\", \"P\"], [\"Q\", \"R\", \"S\", \"T\"], [\"U\", \"V\", \"W\", \"X\"]],\n", + " [[\"Y\", \"Z\", \"_\", \"_\"], [\"_\", \"_\", \"_\", \"_\"], [\"_\", \"_\", \"_\", \"_\"]],\n", + " ],\n", + " ]\n", + ")\n", "\n", "# print U\n", "print(fdim_array[0][1][2][0])" diff --git a/core_libs/numpy/practice/04_numpy_multi_dim_indexing.ipynb b/core_libs/numpy/practice/04_numpy_multi_dim_indexing.ipynb index f53801f..c2aac6a 100644 --- a/core_libs/numpy/practice/04_numpy_multi_dim_indexing.ipynb +++ b/core_libs/numpy/practice/04_numpy_multi_dim_indexing.ipynb @@ -64,24 +64,28 @@ "import numpy as np\n", "\n", "# matrix\n", - "matrix = np.array([['A', 'B', 'C'], \n", - " ['D', 'E', 'F'], \n", - " ['G', 'H', 'I'], \n", - " ['J', 'K', 'L'], \n", - " ['M', 'N', 'O'], \n", - " ['P', 'Q', 'R'], \n", - " ['S', 'T', 'U'], \n", - " ['V', 'W', 'X'], \n", - " ['Y', 'Z', ' ']])\n", + "matrix = np.array(\n", + " [\n", + " [\"A\", \"B\", \"C\"],\n", + " [\"D\", \"E\", \"F\"],\n", + " [\"G\", \"H\", \"I\"],\n", + " [\"J\", \"K\", \"L\"],\n", + " [\"M\", \"N\", \"O\"],\n", + " [\"P\", \"Q\", \"R\"],\n", + " [\"S\", \"T\", \"U\"],\n", + " [\"V\", \"W\", \"X\"],\n", + " [\"Y\", \"Z\", \" \"],\n", + " ]\n", + ")\n", "\n", "# using multidimensional indexing\n", - "print(matrix[4,1])\n", + "print(matrix[4, 1])\n", "\n", "# print last row\n", "print(matrix[-1])\n", "\n", "# print O\n", - "print(matrix[4, -1]) # first get full list at index 4 and then print its last value using -1." + "print(matrix[4, -1]) # first get full list at index 4 and then print its last value using -1." ] }, { diff --git a/core_libs/numpy/practice/05_numpy_array_slicing.ipynb b/core_libs/numpy/practice/05_numpy_array_slicing.ipynb index 052106a..19c3468 100644 --- a/core_libs/numpy/practice/05_numpy_array_slicing.ipynb +++ b/core_libs/numpy/practice/05_numpy_array_slicing.ipynb @@ -70,19 +70,14 @@ "import numpy as np\n", "\n", "# 2d array: 4x4 matrix\n", - "matrix = np.array([\n", - " [1, 2, 3, 4],\n", - " [5, 6, 7, 8],\n", - " [9, 10, 11, 12],\n", - " [13, 14, 15, 16]\n", - " ])\n", + "matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])\n", "\n", - "print(matrix.shape) # (4, 4)\n", - "print(matrix.ndim) # 2\n", - "print(matrix.dtype) # int64\n", - "print(matrix.size) # 4x4 = 16\n", - "print(matrix.itemsize) # 8 bytes\n", - "print(matrix.data) # " + "print(matrix.shape) # (4, 4)\n", + "print(matrix.ndim) # 2\n", + "print(matrix.dtype) # int64\n", + "print(matrix.size) # 4x4 = 16\n", + "print(matrix.itemsize) # 8 bytes\n", + "print(matrix.data) # " ] }, { @@ -292,12 +287,7 @@ ], "source": [ "# recreate it\n", - "matrix = np.array([\n", - " [1, 2, 3, 4],\n", - " [5, 6, 7, 8],\n", - " [9, 10, 11, 12],\n", - " [13, 14, 15, 16]\n", - " ])\n", + "matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])\n", "\n", "print(matrix.shape)" ] @@ -318,7 +308,7 @@ ], "source": [ "# print first column\n", - "print(matrix[:, 0]) # select all rows using `:` or entire matrix then access column 0" + "print(matrix[:, 0]) # select all rows using `:` or entire matrix then access column 0" ] }, { @@ -359,7 +349,7 @@ "source": [ "# print last column reversed\n", "last_column = matrix[:, -1]\n", - "reversed_column = np.flip(last_column) # reverse using np.flip()\n", + "reversed_column = np.flip(last_column) # reverse using np.flip()\n", "print(reversed_column)\n", "\n", "\n", @@ -367,11 +357,11 @@ "last_col = matrix[:, -1]\n", "print(last_col[::-1])\n", "\n", - "# OR: using single slicing line \n", - "print(matrix[::-1, -1]) # first reverse whole matrix using `::-1` and then print last column `-1`\n", + "# OR: using single slicing line\n", + "print(matrix[::-1, -1]) # first reverse whole matrix using `::-1` and then print last column `-1`\n", "\n", "# (Note: slicing applies to each list separately)\n", - "# if 2d matrix then [start:stop:step][start:stop:step] \n", + "# if 2d matrix then [start:stop:step][start:stop:step]\n", "# OR numpy way[start:stop:step, start:stop:step]\n", "\n", "# if there are even higher dimensions then same rule will be applied." @@ -393,12 +383,7 @@ ], "source": [ "# recreate it\n", - "matrix = np.array([\n", - " [1, 2, 3, 4],\n", - " [5, 6, 7, 8],\n", - " [9, 10, 11, 12],\n", - " [13, 14, 15, 16]\n", - " ])\n", + "matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])\n", "\n", "\n", "# print last row reversed\n", diff --git a/core_libs/numpy/practice/06_numpy_arithematic.ipynb b/core_libs/numpy/practice/06_numpy_arithematic.ipynb index 0489b48..1a2e0c8 100644 --- a/core_libs/numpy/practice/06_numpy_arithematic.ipynb +++ b/core_libs/numpy/practice/06_numpy_arithematic.ipynb @@ -39,7 +39,7 @@ "print(array / 2)\n", "print(array * 3)\n", "print(array // 2)\n", - "print(array ** 2)" + "print(array**2)" ] }, { diff --git a/core_libs/numpy/quicks/02_numpy_constants.py b/core_libs/numpy/quicks/02_numpy_constants.py index 3dd0eba..6ae55f3 100644 --- a/core_libs/numpy/quicks/02_numpy_constants.py +++ b/core_libs/numpy/quicks/02_numpy_constants.py @@ -1,21 +1,21 @@ # For more check NumPy official documentation on constants -# https://numpy.org/doc/stable/reference/constants.html +# https://numpy.org/doc/stable/reference/constants.html import numpy as np # PI -print(np.pi) # 3.141592653589793 +print(np.pi) # 3.141592653589793 # Euler's number -print(np.e) # 2.718281828459045 +print(np.e) # 2.718281828459045 -print(np.euler_gamma) # 0.5772156649015329 +print(np.euler_gamma) # 0.5772156649015329 # IEEE 754 floating point representation of (positive) infinity -print(np.inf) # inf +print(np.inf) # inf # IEEE 754 floating point representation of Not a Number (NaN) -print(np.nan) # nan +print(np.nan) # nan # A convenient alias for None, useful for indexing arrays -print(np.newaxis) # None \ No newline at end of file +print(np.newaxis) # None diff --git a/core_libs/pandas/pandas.ipynb b/core_libs/pandas/pandas.ipynb index e69de29..9ff4d73 100644 --- a/core_libs/pandas/pandas.ipynb +++ b/core_libs/pandas/pandas.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/core_libs/pytroch/00_tensor/01.py b/core_libs/pytroch/00_tensor/01.py index d11e415..90e9e87 100644 --- a/core_libs/pytroch/00_tensor/01.py +++ b/core_libs/pytroch/00_tensor/01.py @@ -21,6 +21,6 @@ a = torch.tensor([1, 2, 3]) b = torch.tensor([4, 5, 6]) -print(a+b) +print(a + b) -# output: tensor([5, 7, 9]) \ No newline at end of file +# output: tensor([5, 7, 9]) diff --git a/core_libs/pytroch/00_tensor/02.py b/core_libs/pytroch/00_tensor/02.py index b77f179..f9836da 100644 --- a/core_libs/pytroch/00_tensor/02.py +++ b/core_libs/pytroch/00_tensor/02.py @@ -2,4 +2,4 @@ data = [1, 2, 3] -print(torch.tensor(data)) \ No newline at end of file +print(torch.tensor(data)) diff --git a/core_libs/pytroch/projects/main.py b/core_libs/pytroch/projects/main.py index f53a53f..5d9e6df 100644 --- a/core_libs/pytroch/projects/main.py +++ b/core_libs/pytroch/projects/main.py @@ -1,19 +1,20 @@ # 1. Load and Transform the Data -import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torchvision import datasets, transforms # Define a transform to normalize the data -transform = transforms.Compose([ - transforms.ToTensor(), - transforms.Normalize((0.1307,), (0.3081,)) # MNIST mean and std dev -]) +transform = transforms.Compose( + [ + transforms.ToTensor(), + transforms.Normalize((0.1307,), (0.3081,)), # MNIST mean and std dev + ] +) # Download and load the training and test data -train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) -test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform) +train_dataset = datasets.MNIST(root="./data", train=True, download=True, transform=transform) +test_dataset = datasets.MNIST(root="./data", train=False, download=True, transform=transform) train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=1000, shuffle=False) @@ -26,7 +27,7 @@ def __init__(self): self.flatten = nn.Flatten() self.fc1 = nn.Linear(28 * 28, 128) self.relu = nn.ReLU() - self.fc2 = nn.Linear(128, 10) # 10 output classes (digits 0-9) + self.fc2 = nn.Linear(128, 10) # 10 output classes (digits 0-9) def forward(self, x): x = self.flatten(x) @@ -35,6 +36,7 @@ def forward(self, x): x = self.fc2(x) return x + model = MNISTNetwork() @@ -50,6 +52,6 @@ def forward(self, x): loss = criterion(output, target) loss.backward() optimizer.step() - + if batch_idx % 200 == 0: print(f"Batch {batch_idx}/{len(train_loader)} - Loss: {loss.item():.4f}") diff --git a/core_modules/os/os.ipynb b/core_modules/os/os.ipynb index e69de29..9ff4d73 100644 --- a/core_modules/os/os.ipynb +++ b/core_modules/os/os.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/core_modules/pathlib/pathlib.ipynb b/core_modules/pathlib/pathlib.ipynb index 1671ba2..bc78381 100644 --- a/core_modules/pathlib/pathlib.ipynb +++ b/core_modules/pathlib/pathlib.ipynb @@ -38,8 +38,8 @@ } ], "source": [ - "from pathlib import Path\n", "import os\n", + "from pathlib import Path\n", "\n", "# user's home dir\n", "home_dir = Path.home()\n", @@ -68,7 +68,7 @@ } ], "source": [ - "# \n", + "#\n", "os.cpu_count()" ] } diff --git a/custom_module_import_export/main.py b/custom_module_import_export/main.py index 8a60b49..a364d3f 100644 --- a/custom_module_import_export/main.py +++ b/custom_module_import_export/main.py @@ -13,4 +13,4 @@ except ZeroDivisionError as error: print(error) finally: - pass \ No newline at end of file + pass diff --git a/custom_module_import_export/math_utils.py b/custom_module_import_export/math_utils.py index d483e06..dd6a1c0 100644 --- a/custom_module_import_export/math_utils.py +++ b/custom_module_import_export/math_utils.py @@ -1,12 +1,15 @@ def add(x: int, y: int): return x + y + def sub(x: int, y: int): return x - y + def mul(x: int, y: int): return x * y + def div(x: int, y: int): if y == 0: raise ZeroDivisionError diff --git a/debugging/breakpoint/init.py b/debugging/breakpoint/init.py index 055675d..1937ac0 100644 --- a/debugging/breakpoint/init.py +++ b/debugging/breakpoint/init.py @@ -1,14 +1,15 @@ def floor_division(a: int, b: int) -> int: - breakpoint() # Execution pauses here - + breakpoint() # Execution pauses here + if b == 0: raise ZeroDivisionError("Cannot divide a number by zero.") return a // b + try: - print(floor_division(10,0)) + print(floor_division(10, 0)) except ZeroDivisionError as e: print("Error:", e) finally: - print("--- Task completed ---") \ No newline at end of file + print("--- Task completed ---") diff --git a/debugging/breakpoint/intro.md b/debugging/breakpoint/intro.md index 100a16b..42ce58c 100644 --- a/debugging/breakpoint/intro.md +++ b/debugging/breakpoint/intro.md @@ -6,9 +6,9 @@ Place breakpoint() right before the point of confusion: ```py def floor_division(a: int, b: int) -> int: - - breakpoint() # Execution pauses here - + + breakpoint() # Execution pauses here + if b == 0: raise ZeroDivisionError return a // b diff --git a/debugging/module-errors/problem.md b/debugging/module-errors/problem.md index 1ef31ce..ffe2220 100644 --- a/debugging/module-errors/problem.md +++ b/debugging/module-errors/problem.md @@ -8,10 +8,11 @@ Actual python that caused the error: from src.core import JSON_DATA_FILE_PATH import json + class ProductRepository: # 1. get all products def get_all(self) -> dict | None: - + payload = None if JSON_DATA_FILE_PATH: @@ -24,13 +25,11 @@ class ProductRepository: # print(payload[1:5]) # print("-"*25) - return { - "total_products": len(payload), - "products": payload - } + return {"total_products": len(payload), "products": payload} else: return None + # Debugging product = ProductRepository() diff --git a/fastapi-projects/1-project/src/main.py b/fastapi-projects/1-project/src/main.py index b338acc..01bc86d 100644 --- a/fastapi-projects/1-project/src/main.py +++ b/fastapi-projects/1-project/src/main.py @@ -7,20 +7,22 @@ description="First Project", version="0.1.0", docs_url="/docs", - redoc_url="/redoc" + redoc_url="/redoc", ) # products list products = [ Product(id=1, name="Phone", description="Budget Phone", price=499.9, quantity=100), - Product(id=2, name="Laptop", description="Gaming Laptop", price=999.9, quantity=35) + Product(id=2, name="Laptop", description="Gaming Laptop", price=999.9, quantity=35), ] + # test route @app.get("/") def home(): return "homepage" + # return products @app.get("/products") async def get_all_products(): diff --git a/fastapi-projects/1-project/src/models.py b/fastapi-projects/1-project/src/models.py index 77beecc..021cd3e 100644 --- a/fastapi-projects/1-project/src/models.py +++ b/fastapi-projects/1-project/src/models.py @@ -11,4 +11,4 @@ def __init__(self, id: int, name: str, description: str, price: float, quantity: self.name = name self.description = description self.price = price - self.quantity = quantity \ No newline at end of file + self.quantity = quantity diff --git a/fastapi-projects/2-project/src/main.py b/fastapi-projects/2-project/src/main.py index 166ba52..827ed7d 100644 --- a/fastapi-projects/2-project/src/main.py +++ b/fastapi-projects/2-project/src/main.py @@ -4,17 +4,20 @@ app = FastAPI() + # test api @app.get("/") def home(): return "Homepage" + products = [ Product(id=1, name="Phone", description="Budget Phone", price=499.9, quantity=100), Product(id=2, name="Laptop", description="Gaming Laptop", price=999.9, quantity=35), - Product(id=3, name="Laptop", description="Gaming Laptop", price=999.9, quantity=35) + Product(id=3, name="Laptop", description="Gaming Laptop", price=999.9, quantity=35), ] + # return all products @app.get("/products") def get_all_products(): @@ -27,7 +30,7 @@ def get_all_products(): def get_product_by_id(id: int): for p in products: if p.id == id: - return p + return p raise HTTPException(status_code=404, detail="Product not found") @@ -44,4 +47,4 @@ def add_product(product: Product): # return {"status": 200, "message": "Product saved successfully!", "data": product} # use pydantic so fastapi automatically converts pydantic attr's to json - return ApiResponse(status=200, message="Product saved successfully!", data=product) \ No newline at end of file + return ApiResponse(status=200, message="Product saved successfully!", data=product) diff --git a/fastapi-projects/2-project/src/models/__init__.py b/fastapi-projects/2-project/src/models/__init__.py index 51a3f0d..12dd456 100644 --- a/fastapi-projects/2-project/src/models/__init__.py +++ b/fastapi-projects/2-project/src/models/__init__.py @@ -1,3 +1,3 @@ from .product import Product -__all__ = ["Product"] \ No newline at end of file +__all__ = ["Product"] diff --git a/fastapi-projects/2-project/src/models/product.py b/fastapi-projects/2-project/src/models/product.py index 166fe9d..a7d0f66 100644 --- a/fastapi-projects/2-project/src/models/product.py +++ b/fastapi-projects/2-project/src/models/product.py @@ -1,6 +1,7 @@ # pydantic is validator for the data used to define the specs or interfaces from pydantic import BaseModel + class Product(BaseModel): id: int name: str @@ -8,4 +9,4 @@ class Product(BaseModel): price: float quantity: int - # here no need to define constructor as pydantic takes care of it. For ref, look at 1-project, we defined constructor and then invoked that in main.py. However, now we don't need it. \ No newline at end of file + # here no need to define constructor as pydantic takes care of it. For ref, look at 1-project, we defined constructor and then invoked that in main.py. However, now we don't need it. diff --git a/fastapi-projects/2-project/src/schemas/__init__.py b/fastapi-projects/2-project/src/schemas/__init__.py index 2be5bbe..194b518 100644 --- a/fastapi-projects/2-project/src/schemas/__init__.py +++ b/fastapi-projects/2-project/src/schemas/__init__.py @@ -1,3 +1,3 @@ from .response import ApiResponse -__all__ = ["ApiResponse"] \ No newline at end of file +__all__ = ["ApiResponse"] diff --git a/fastapi-projects/2-project/src/schemas/response.py b/fastapi-projects/2-project/src/schemas/response.py index 79ca999..22d5868 100644 --- a/fastapi-projects/2-project/src/schemas/response.py +++ b/fastapi-projects/2-project/src/schemas/response.py @@ -1,9 +1,11 @@ -from typing import Generic, TypeVar, Optional +from typing import Generic, Optional, TypeVar + from pydantic import BaseModel T = TypeVar("T") + class ApiResponse(BaseModel, Generic[T]): status: int = 200 message: str - data: Optional[T] = None \ No newline at end of file + data: Optional[T] = None diff --git a/fastapi-projects/3-project/scripts/inspect_data.py b/fastapi-projects/3-project/scripts/inspect_data.py index 6ac4c66..4e7b36a 100644 --- a/fastapi-projects/3-project/scripts/inspect_data.py +++ b/fastapi-projects/3-project/scripts/inspect_data.py @@ -16,10 +16,10 @@ json_files: list = [] csv_files: list = [] + # ls: list dir and files and generate useful info of data dir def metadata_data_generator(): if data_dir.is_dir(): - print(f"\n> ls {data_dir}\n") # .iterdir() yields Path objects one by one for item in data_dir.iterdir(): @@ -45,6 +45,7 @@ def metadata_data_generator(): # display error in-case if its not a directory print(f"Error: No data directory found at {data_dir}\nFix: check core/data.py to fix the error") + metadata_data_generator() @@ -58,4 +59,4 @@ def metadata_data_generator(): 📄 data.csv Json files: ['data.json'] CSV files: ['data.csv'] -""" \ No newline at end of file +""" diff --git a/fastapi-projects/3-project/src/core/__init__.py b/fastapi-projects/3-project/src/core/__init__.py index edeac78..d3dfb25 100644 --- a/fastapi-projects/3-project/src/core/__init__.py +++ b/fastapi-projects/3-project/src/core/__init__.py @@ -1,3 +1,3 @@ from .config import DATA_DIR -__all__ = ["DATA_DIR"] \ No newline at end of file +__all__ = ["DATA_DIR"] diff --git a/fastapi-projects/3-project/src/core/config.py b/fastapi-projects/3-project/src/core/config.py index 3d6d1b0..efbcfe1 100644 --- a/fastapi-projects/3-project/src/core/config.py +++ b/fastapi-projects/3-project/src/core/config.py @@ -1,5 +1,4 @@ from pathlib import Path -import json # Get absolute path *this file core_dir = Path(__file__).resolve().parent @@ -11,4 +10,4 @@ data_dir = (project_root / "data" / "data.json").resolve() # resolve path for /data/data.json -DATA_DIR: Path | None = data_dir if data_dir.exists() and data_dir.is_file and data_dir.suffix == ".json" else None \ No newline at end of file +DATA_DIR: Path | None = data_dir if data_dir.exists() and data_dir.is_file and data_dir.suffix == ".json" else None diff --git a/fastapi-projects/3-project/src/main.py b/fastapi-projects/3-project/src/main.py index 4d25ac1..59f77a6 100644 --- a/fastapi-projects/3-project/src/main.py +++ b/fastapi-projects/3-project/src/main.py @@ -2,14 +2,13 @@ from fastapi import FastAPI, HTTPException -from src.models import Product -from src.schemas import ApiResponse from src.repositories import ProductRepository - +from src.schemas import ApiResponse # instantiate app app = FastAPI() + # test api @app.get("/") def home(): @@ -24,29 +23,24 @@ def home(): # API Endpoints / Get Methods # # ======================================================================================= + # all products @app.get("/products") def get_all_products(): return ApiResponse(status_code=200, message="All products", data=product.get_all()) - # pagination @app.get("/products/search/page") def get_product_by_pagination(q: str, skip: int = 0, limit: int = 10): filtered_products: dict | None = product.get_by_pagination(q=q, skip=skip, limit=limit) if filtered_products and filtered_products["total_matches"] > 0 and len(filtered_products["results"]) > 0: - return ApiResponse( - status_code=200, - message="Paginated products", - data=filtered_products - ) + return ApiResponse(status_code=200, message="Paginated products", data=filtered_products) else: raise HTTPException(status_code=404, detail=f"No product matched with provided query: {q}") - # search a product @app.get("/products/search") def get_product_by_query(q: str): @@ -56,16 +50,15 @@ def get_product_by_query(q: str): if filtered_products: if len(filtered_products) > 0: return ApiResponse(status_code=200, message="Matched products", data=filtered_products) - else: + else: raise HTTPException(status_code=404, detail=f"No product matched with provided query: {q}") - # product by id @app.get("/products/{id}") def get_product_by_id(id: int): - - p : dict | None = product.get_by_id(id=id) + + p: dict | None = product.get_by_id(id=id) if p: return ApiResponse(status_code=200, message="Matched product", data=p) diff --git a/fastapi-projects/3-project/src/models/__init__.py b/fastapi-projects/3-project/src/models/__init__.py index 51a3f0d..12dd456 100644 --- a/fastapi-projects/3-project/src/models/__init__.py +++ b/fastapi-projects/3-project/src/models/__init__.py @@ -1,3 +1,3 @@ from .product import Product -__all__ = ["Product"] \ No newline at end of file +__all__ = ["Product"] diff --git a/fastapi-projects/3-project/src/models/product.py b/fastapi-projects/3-project/src/models/product.py index 22bd51f..dc15c84 100644 --- a/fastapi-projects/3-project/src/models/product.py +++ b/fastapi-projects/3-project/src/models/product.py @@ -1,9 +1,10 @@ from pydantic import BaseModel + class Product(BaseModel): id: int name: str description: str price: float category: str - image_url: str \ No newline at end of file + image_url: str diff --git a/fastapi-projects/3-project/src/repositories/__init__.py b/fastapi-projects/3-project/src/repositories/__init__.py index 5df6221..73b66f6 100644 --- a/fastapi-projects/3-project/src/repositories/__init__.py +++ b/fastapi-projects/3-project/src/repositories/__init__.py @@ -1,3 +1,3 @@ from .product import ProductRepository -__all__ = ["ProductRepository"] \ No newline at end of file +__all__ = ["ProductRepository"] diff --git a/fastapi-projects/3-project/src/repositories/product.py b/fastapi-projects/3-project/src/repositories/product.py index ee0dbb3..2caa102 100644 --- a/fastapi-projects/3-project/src/repositories/product.py +++ b/fastapi-projects/3-project/src/repositories/product.py @@ -1,9 +1,10 @@ -from src.core import DATA_DIR import json +from src.core import DATA_DIR + + # json based class ProductRepository: - # 1. get all products, read data from data/data.json file and return json data def get_all(self) -> list | None: @@ -17,7 +18,7 @@ def get_all(self) -> list | None: return payload else: return None - + # 2. get a product by an id def get_by_id(self, id: int) -> dict | None: @@ -32,17 +33,17 @@ def get_by_id(self, id: int) -> dict | None: # find product by id for item in payload: - if item['id'] == id: + if item["id"] == id: return item else: - return None - + return None + # 3. search product def get_by_query(self, q: str) -> list | None: - + # lowercase query q = q.lower() - + payload = None if DATA_DIR: @@ -60,17 +61,18 @@ def get_by_query(self, q: str) -> list | None: price = str(item["price"]) # filter products - if (q in id or - q in price or - q in item["name"].lower() or - q in item["description"].lower() or - q in item["category"].lower()): + if ( + q in id + or q in price + or q in item["name"].lower() + or q in item["description"].lower() + or q in item["category"].lower() + ): products.append(item) return products else: - return None # 4. product with pagination @@ -95,19 +97,20 @@ def get_by_pagination(self, q: str, skip: int = 0, limit: int = 10) -> dict | No price = str(item["price"]) # filter products - if (q in id or - q in price or - q in item["name"].lower() or - q in item["description"].lower() or - q in item["category"].lower()): - + if ( + q in id + or q in price + or q in item["name"].lower() + or q in item["description"].lower() + or q in item["category"].lower() + ): products.append(item) return { "total_matches": len(products), "skip": skip, "limit": limit, - "results": products[skip:skip+limit] if len(products) > 10 else products + "results": products[skip : skip + limit] if len(products) > 10 else products, } else: diff --git a/fastapi-projects/3-project/src/schemas/__init__.py b/fastapi-projects/3-project/src/schemas/__init__.py index 2be5bbe..194b518 100644 --- a/fastapi-projects/3-project/src/schemas/__init__.py +++ b/fastapi-projects/3-project/src/schemas/__init__.py @@ -1,3 +1,3 @@ from .response import ApiResponse -__all__ = ["ApiResponse"] \ No newline at end of file +__all__ = ["ApiResponse"] diff --git a/fastapi-projects/3-project/src/schemas/response.py b/fastapi-projects/3-project/src/schemas/response.py index 9e2a3c9..13d2a13 100644 --- a/fastapi-projects/3-project/src/schemas/response.py +++ b/fastapi-projects/3-project/src/schemas/response.py @@ -1,10 +1,12 @@ -from typing import Generic, TypeVar, Optional +from typing import Generic, Optional, TypeVar + from pydantic import BaseModel T = TypeVar("T") + class ApiResponse(BaseModel, Generic[T]): # attributes status_code: int = 200 message: str - data: Optional[T] = None \ No newline at end of file + data: Optional[T] = None diff --git a/fastapi-projects/fastapi_setup.md b/fastapi-projects/fastapi_setup.md index 9cc8a39..8aa8fe1 100644 --- a/fastapi-projects/fastapi_setup.md +++ b/fastapi-projects/fastapi_setup.md @@ -29,6 +29,7 @@ app = FastAPI() + @app.get("/") def home(): return "Homepage" diff --git a/file_handling/00_basic_file_handling/BinaryFileHandling.ipynb b/file_handling/00_basic_file_handling/BinaryFileHandling.ipynb index 07d5bab..faa765a 100644 --- a/file_handling/00_basic_file_handling/BinaryFileHandling.ipynb +++ b/file_handling/00_basic_file_handling/BinaryFileHandling.ipynb @@ -158,7 +158,7 @@ "metadata": {}, "outputs": [], "source": [ - "chunk_size = 4096 # Read 4kb at a time\n", + "chunk_size = 4096 # Read 4kb at a time\n", "\n", "with open(\"large_file.bin\", \"rb\") as file:\n", " while True:\n", diff --git a/file_handling/00_basic_file_handling/main.ipynb b/file_handling/00_basic_file_handling/main.ipynb index 14900d8..0f77b03 100644 --- a/file_handling/00_basic_file_handling/main.ipynb +++ b/file_handling/00_basic_file_handling/main.ipynb @@ -133,7 +133,7 @@ "source": [ "with open(filePath, \"r\", encoding=\"utf-8\") as file:\n", " for line in file:\n", - " print(line.strip()) # strip() removes trailing newlines (\\n)" + " print(line.strip()) # strip() removes trailing newlines (\\n)" ] }, { @@ -185,7 +185,7 @@ "with open(filePath, \"w\") as file:\n", " file.write(\"Hello, world\\n\")\n", "\n", - "# confirm after write \n", + "# confirm after write\n", "with open(filePath, \"r\", encoding=\"utf-8\") as file:\n", " for line in file:\n", " print(line.strip())" diff --git a/file_handling/01_csv/main.ipynb b/file_handling/01_csv/main.ipynb index 603198d..ba329ff 100644 --- a/file_handling/01_csv/main.ipynb +++ b/file_handling/01_csv/main.ipynb @@ -51,12 +51,12 @@ " [\"Name\", \"Age\", \"City\"],\n", " [\"Ali\", \"24\", \"Rawalpindi\"],\n", " [\"Hamza\", \"23\", \"Kohat\"],\n", - " [\"Abdullah\", \"22\", \"Sialkot\"]\n", + " [\"Abdullah\", \"22\", \"Sialkot\"],\n", "]\n", "\n", - "with open('./files/output.csv', mode=\"w\", newline='', encoding=\"utf-8\") as file:\n", + "with open(\"./files/output.csv\", mode=\"w\", newline=\"\", encoding=\"utf-8\") as file:\n", " writer = csv.writer(file)\n", - " writer.writerows(data) # write multiple rows" + " writer.writerows(data) # write multiple rows" ] }, { @@ -84,16 +84,16 @@ "source": [ "import csv\n", "\n", - "fieldnames = [\"Name\", \"Age\", \"City\"] # header schema\n", + "fieldnames = [\"Name\", \"Age\", \"City\"] # header schema\n", "rows = [\n", " {\"Name\": \"Ali\", \"Age\": \"24\", \"City\": \"Rawalpindi\"},\n", " {\"Name\": \"Hamza\", \"Age\": \"23\", \"City\": \"Kohat\"},\n", - " {\"Name\": \"Abdullah\", \"Age\": \"22\", \"City\": \"Sialkot\"}\n", + " {\"Name\": \"Abdullah\", \"Age\": \"22\", \"City\": \"Sialkot\"},\n", "]\n", "\n", "with open(\"./files/output_dict.csv\", mode=\"w\", newline=\"\", encoding=\"utf-8\") as file:\n", " writer = csv.DictWriter(file, fieldnames=fieldnames)\n", - " writer.writeheader() # writes the top header\n", + " writer.writeheader() # writes the top header\n", " writer.writerows(rows)" ] }, diff --git a/file_handling/02_json/main.ipynb b/file_handling/02_json/main.ipynb index 40e2414..dd5c007 100644 --- a/file_handling/02_json/main.ipynb +++ b/file_handling/02_json/main.ipynb @@ -68,8 +68,8 @@ "# Convert the string into a Python dictionary\n", "data = json.loads(json_string)\n", "\n", - "print(f\"{\"Index\":<10} | {\"Field\":<15} | {\"Values\"}\")\n", - "print(\"-\"*48)\n", + "print(f\"{'Index':<10} | {'Field':<15} | {'Values'}\")\n", + "print(\"-\" * 48)\n", "for ind, (k, v) in enumerate(data.items()):\n", " print(f\"{ind:<10} | {k:<15} | {v}\")" ] @@ -110,12 +110,7 @@ "source": [ "import json\n", "\n", - "user_dict = {\n", - " \"name\": \"Bob\",\n", - " \"age\": 30,\n", - " \"has_license\": True,\n", - " \"hobbies\": None\n", - "}\n", + "user_dict = {\"name\": \"Bob\", \"age\": 30, \"has_license\": True, \"hobbies\": None}\n", "\n", "# Convert the dictionary into a JSON formatted string\n", "raw_json = json.dumps(user_dict)\n", @@ -157,15 +152,10 @@ "source": [ "import json\n", "\n", - "payload = {\n", - " \"name\": \"Bob\",\n", - " \"age\": 30,\n", - " \"has_license\": True,\n", - " \"hobbies\": None\n", - "}\n", + "payload = {\"name\": \"Bob\", \"age\": 30, \"has_license\": True, \"hobbies\": None}\n", "\n", "with open(\"./files/payload.json\", mode=\"w\") as file:\n", - " json.dump(payload, file, indent=4) # Saves directly into the file" + " json.dump(payload, file, indent=4) # Saves directly into the file" ] }, { diff --git a/functions/first_class_functions/first_class_functions.ipynb b/functions/first_class_functions/first_class_functions.ipynb index 8abb186..c832e2e 100644 --- a/functions/first_class_functions/first_class_functions.ipynb +++ b/functions/first_class_functions/first_class_functions.ipynb @@ -48,6 +48,7 @@ "def greet(name):\n", " return f\"Hello, {name}\"\n", "\n", + "\n", "# Assign the function reference to a variable\n", "say_hello = greet\n", "\n", @@ -83,10 +84,12 @@ "def greeting(name):\n", " return f\"Hello, {name}\"\n", "\n", + "\n", "# Higher order function that accepts a function as 'func_argument'\n", "def execute_greeting(func_argument, username):\n", " return func_argument(username)\n", "\n", + "\n", "# Pass the 'greeting' function object into 'execute_greeting'\n", "print(execute_greeting(greeting, \"Saqib Bedar\"))" ] @@ -120,10 +123,12 @@ "# closure\n", "def multiplier_factory(factor):\n", " # Inner function that captures 'factor' variable\n", - " def multiply_by(number): \n", + " def multiply_by(number):\n", " return number * factor\n", + "\n", " return multiply_by # Return the inner function without calling it\n", "\n", + "\n", "double = multiplier_factory(2)\n", "triple = multiplier_factory(3)\n", "\n", @@ -156,18 +161,22 @@ } ], "source": [ - "def add(a, b): return a + b\n", - "def sub(a, b): return a - b\n", - "def mul(a, b): return a * b\n", + "def add(a, b):\n", + " return a + b\n", + "\n", + "\n", + "def sub(a, b):\n", + " return a - b\n", + "\n", + "\n", + "def mul(a, b):\n", + " return a * b\n", + "\n", "\n", "# store functions as values inside a dictionary (remember JS)\n", - "math_operators = {\n", - " \"add\": add,\n", - " \"sub\": sub,\n", - " \"mul\": mul\n", - "}\n", + "math_operators = {\"add\": add, \"sub\": sub, \"mul\": mul}\n", "\n", - "# Access and call the function \n", + "# Access and call the function\n", "result = math_operators[\"add\"](2, 2)\n", "\n", "print(result)" diff --git a/functions/generators/benchmark.md b/functions/generators/benchmark.md index 54dc8af..9601be4 100644 --- a/functions/generators/benchmark.md +++ b/functions/generators/benchmark.md @@ -36,13 +36,16 @@ def data_generator(): unpack_time = timeit.timeit("[*data_generator()]", setup=setup_code, number=1000) list_time = timeit.timeit("list(data_generator())", setup=setup_code, number=1000) -loop_setup = setup_code + """ +loop_setup = ( + setup_code + + """ def manual_loop(): result = [] for item in data_generator(): result.append(item) return result """ +) loop_time = timeit.timeit("manual_loop()", setup=loop_setup, number=1000) diff --git a/functions/generators/generators.ipynb b/functions/generators/generators.ipynb index 599a229..c5e1665 100644 --- a/functions/generators/generators.ipynb +++ b/functions/generators/generators.ipynb @@ -53,9 +53,10 @@ "# Defining the generator function\n", "def gen_int(start=0, stop=0):\n", " while start <= stop:\n", - " yield start # Pauses here and outputs the value\n", + " yield start # Pauses here and outputs the value\n", " start += 1\n", "\n", + "\n", "# Creating the generator object\n", "num = gen_int(1, 5)\n", "\n", @@ -147,6 +148,7 @@ " for line in file:\n", " yield line # Memory-safe streaming\n", "\n", + "\n", "# Processing the stream without overloading RAM\n", "for log_line in read_large_file(\"huge_system_log.txt\"):\n", " if \"ERROR\" in log_line:\n", @@ -199,6 +201,7 @@ " yield count\n", " count += 1\n", "\n", + "\n", "# generator object\n", "counter = count_upto(5)\n", "\n", @@ -384,7 +387,8 @@ " yield 2\n", " yield 3\n", "\n", - "# unpack \n", + "\n", + "# unpack\n", "a, b, c = gen_nums()\n", "\n", "print(a, b, c)" @@ -464,7 +468,7 @@ "my_gen = (x**2 for x in range(10))\n", "\n", "# unpacking into a list\n", - "num_lst = [*my_gen] # used * before variable/label name to get rest of values\n", + "num_lst = [*my_gen] # used * before variable/label name to get rest of values\n", "print(num_lst)" ] }, @@ -525,6 +529,7 @@ "def add_three(x, y, z):\n", " return x + y + z\n", "\n", + "\n", "data_gen = (var for var in [1, 2, 3])\n", "\n", "# Unpacks into x=1, y=2, z=3\n", @@ -604,13 +609,16 @@ "list_time = timeit.timeit(\"list(data_generator())\", setup=setup_code, number=1000)\n", "\n", "# Test 3: Manual For Loop\n", - "loop_setup = setup_code + \"\"\"\n", + "loop_setup = (\n", + " setup_code\n", + " + \"\"\"\n", "def manual_loop():\n", " result = []\n", " for item in data_generator():\n", " result.append(item)\n", " return result\n", "\"\"\"\n", + ")\n", "loop_time = timeit.timeit(\"manual_loop()\", setup=loop_setup, number=1000)\n", "\n", "print(f\"Star Unpacking: {unpack_time:.4f} seconds\")\n", diff --git a/functions/generators/iterator_optm.md b/functions/generators/iterator_optm.md index 6d3d0e1..ba2fb0d 100644 --- a/functions/generators/iterator_optm.md +++ b/functions/generators/iterator_optm.md @@ -72,6 +72,7 @@ def huge_numbers(): for i in range(1_000_000): yield i + all_values = [*huge_numbers()] ``` @@ -95,6 +96,7 @@ def infinite_counter(): yield n n += 1 + first_five = [*islice(infinite_counter(), 5)] print(first_five) # Output: [1, 2, 3, 4, 5] @@ -119,6 +121,7 @@ from itertools import islice def huge_generator(): return (x for x in range(100_000)) + iterator = huge_generator() while True: diff --git a/functions/lambda/lambda.ipynb b/functions/lambda/lambda.ipynb index c2ad37d..8955748 100644 --- a/functions/lambda/lambda.ipynb +++ b/functions/lambda/lambda.ipynb @@ -53,10 +53,11 @@ "source": [ "# Regular function expression\n", "def power(x):\n", - " return x ** 2 # equivalent to pow(x, 2) or import math and use math.pow(x, 2) and it will return float number\n", + " return x**2 # equivalent to pow(x, 2) or import math and use math.pow(x, 2) and it will return float number\n", + "\n", "\n", "# lambda function\n", - "power_lambda = lambda x: x ** 2\n", + "power_lambda = lambda x: x**2 # noqa: E731\n", "\n", "print(f\"{power(5)=}\")\n", "print(f\"{power_lambda(5)=}\")" @@ -110,7 +111,7 @@ "# list\n", "numbers_lst = [1, 2, 3, 4]\n", "\n", - "squared_lst = list(map(lambda x: x ** 2, numbers_lst))\n", + "squared_lst = list(map(lambda x: x**2, numbers_lst))\n", "\n", "print(f\"{squared_lst=}\")" ] @@ -132,7 +133,7 @@ "source": [ "numbers_tuple = (1, 2, 3, 4)\n", "\n", - "squared_tuple = tuple(map(lambda x: x ** 2, numbers_tuple))\n", + "squared_tuple = tuple(map(lambda x: x**2, numbers_tuple))\n", "\n", "print(f\"{squared_tuple=}\")" ] @@ -154,7 +155,7 @@ "source": [ "numbers_set = {1, 2, 3, 4}\n", "\n", - "squared_set = set(map(lambda x: x ** 2, numbers_set))\n", + "squared_set = set(map(lambda x: x**2, numbers_set))\n", "\n", "print(f\"{squared_set=}\")" ] @@ -249,11 +250,7 @@ ], "source": [ "# prices are in PKR\n", - "prices = {\n", - " \"apple\": 350,\n", - " \"banana\": 150,\n", - " \"cherry\": 450\n", - "}\n", + "prices = {\"apple\": 350, \"banana\": 150, \"cherry\": 450}\n", "\n", "expensive_items = dict(filter(lambda item: item[1] > 200, prices.items()))\n", "\n", @@ -277,11 +274,7 @@ } ], "source": [ - "prices = {\n", - " \"apple\": 1,\n", - " \"banana\": .8,\n", - " \"cherry\": 1.5\n", - "}\n", + "prices = {\"apple\": 1, \"banana\": 0.8, \"cherry\": 1.5}\n", "\n", "for item in prices.items():\n", " print(item[0])" diff --git a/projects/00_first_python_project/main.ipynb b/projects/00_first_python_project/main.ipynb index 7e6bbb8..cc10bd3 100644 --- a/projects/00_first_python_project/main.ipynb +++ b/projects/00_first_python_project/main.ipynb @@ -250,7 +250,7 @@ "prompt = \"Explain why arrays start at 0 in 1 short sentence.\"\n", "output = generator(prompt, max_new_tokens=40)\n", "\n", - "print(output[0]['generated_text'])" + "print(output[0][\"generated_text\"])" ] }, { @@ -310,9 +310,9 @@ } ], "source": [ - "from transformers import AutoTokenizer, AutoModelForCausalLM\n", + "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "\n", - "# define target model \n", + "# define target model\n", "model_name = \"Qwen/Qwen2.5-0.5B-Instruct\"\n", "\n", "# 1. Fetch the Tokenizer paired exactly to this model\n", @@ -364,7 +364,7 @@ "token_ids = tokenizer.encode(text_input)\n", "\n", "print(\"1. Raw Characters:\", text_input)\n", - "print(\"2. Encoded Token IDs:\", token_ids) \n", + "print(\"2. Encoded Token IDs:\", token_ids)\n", "# Notice how a short phrase is mapped into an array of isolated integer integers" ] }, diff --git a/sem-v/00_classification/binaryClassification.py b/sem-v/00_classification/binaryClassification.py index 16add8a..921c5bc 100644 --- a/sem-v/00_classification/binaryClassification.py +++ b/sem-v/00_classification/binaryClassification.py @@ -1,38 +1,40 @@ """ - 1. f_w(x) = sign(w.phi(x)) where w.phi(x) are called score or margin and phi(x) is feature vector or in simple terms array of data and w represents weights - - Overall, f_w(x) is called y_hat. +1. f_w(x) = sign(w.phi(x)) where w.phi(x) are called score or margin and phi(x) is feature vector or in simple terms array of data and w represents weights - 1. We will be given inputs as x(phi(x) or feature vectors) in an array or any data structure. - 2. secondly weight vectors also in an array - 3. Also true_y which is given or sometimes we are asked to find, its a true labeled value which we compare with predicted or y_hat. +Overall, f_w(x) is called y_hat. + +1. We will be given inputs as x(phi(x) or feature vectors) in an array or any data structure. +2. secondly weight vectors also in an array +3. Also true_y which is given or sometimes we are asked to find, its a true labeled value which we compare with predicted or y_hat. """ import math -x = [3,2, -9] +x = [3, 2, -9] weights = [0.1, -0.5, 1] # Input true_y true_y = int(input("enter true_y value[-1 or +1]: ")) + # score/margin: measure model prediction score def score(x, w): sc = 0 # Iterate over x and weights to get score sc = w.phi(x) - for xi, wi in zip(x, w): + for xi, wi in zip(x, w): sc += wi * xi return sc + # predicted output sc = score(x, weights) -# convert to [-1,+1] +# convert to [-1,+1] # y_hat = fw_(x) = sin(w.phi(x)) y_hat = 1 if math.sin(sc) >= 0 else -1 if y_hat == true_y: print("correct") else: - print("wrong") \ No newline at end of file + print("wrong") diff --git a/sem-v/00_classification/perceptron.py b/sem-v/00_classification/perceptron.py index b6e0db2..b44cb5d 100644 --- a/sem-v/00_classification/perceptron.py +++ b/sem-v/00_classification/perceptron.py @@ -1,23 +1,26 @@ """ - The Perceptron update rule: +The Perceptron update rule: - 1. Compute the score (margin): m = w⋅x - 2. Predict: y_hat = sign(m) - 3. If prediction is wrong (y_hat != true_y), then update: w ← w + yx +1. Compute the score (margin): m = w⋅x +2. Predict: y_hat = sign(m) +3. If prediction is wrong (y_hat != true_y), then update: w ← w + yx """ x = [1, 1] y = -1 w = [0, 0] + # Compute margin def score(x, w): return sum(xi * wi for xi, wi in zip(x, w)) + # Predict y_hat def predict(x, w): return 1 if score(x, w) >= 0 else -1 + # Perceptron update max_iters = 10 for _ in range(max_iters): diff --git a/sem-v/00_classification/zero_one_loss.py b/sem-v/00_classification/zero_one_loss.py index c792f82..30abf94 100644 --- a/sem-v/00_classification/zero_one_loss.py +++ b/sem-v/00_classification/zero_one_loss.py @@ -1,38 +1,42 @@ """ - 1. y_hat = fw_(x) = sin(w.phi(x)) - 01Loss = 1[(y_hat)*true_y <= 0] = 1[(w.phi(x)) * y <= 0] +1. y_hat = fw_(x) = sin(w.phi(x)) +01Loss = 1[(y_hat)*true_y <= 0] = 1[(w.phi(x)) * y <= 0] """ import math -x = [3,2, -9] +x = [3, 2, -9] weights = [0.1, -0.5, 1] # Input true_y true_y = int(input("enter true_y value[-1 or +1]: ")) + # score/margin: measure model prediction score def score(x, w): sc = 0 # Iterate over x and weights to get score sc = w.phi(x) - for xi, wi in zip(x, w): + for xi, wi in zip(x, w): sc += wi * xi return sc + # prediction_score prediction_score = score(x, weights) + # zero_one_loss = (w-x)*y def zero_one_loss(prediction_score, true_y): - # convert to [-1,+1] + # convert to [-1,+1] # y_hat = fw_(x) = sin(w.phi(x)) y_hat = 1 if math.sin(prediction_score) >= 0 else -1 - loss = (y_hat * true_y) - + loss = y_hat * true_y + # if positive means no loss return 0 else return 1 return 0 if loss > 0 else 1 + print("score:", prediction_score) print("y_hat:", 1 if prediction_score >= 0 else -1) -print("zero-one loss:", zero_one_loss(prediction_score, true_y)) \ No newline at end of file +print("zero-one loss:", zero_one_loss(prediction_score, true_y)) diff --git a/sem-v/01_regression/regression.py b/sem-v/01_regression/regression.py index e498b7f..016a321 100644 --- a/sem-v/01_regression/regression.py +++ b/sem-v/01_regression/regression.py @@ -1,13 +1,14 @@ """ - y_hat is prediction done by our algorithm, it is defined as: - - y_hat = (w.phi(x)) +y_hat is prediction done by our algorithm, it is defined as: + + y_hat = (w.phi(x)) """ -x = [3,4] +x = [3, 4] w = [0.5, -1.5] -true_y = int(input("What's true_y? ")) # get y input +true_y = int(input("What's true_y? ")) # get y input + # find margin/score w.phi(x) where phi(x) = array of x or feature vectors def score(feature_vectors, weights): @@ -17,6 +18,7 @@ def score(feature_vectors, weights): return result + y_hat = score(x, w) print("Prediction: ", y_hat) diff --git a/sem-v/01_regression/residualSquaredLoss.py b/sem-v/01_regression/residualSquaredLoss.py index 274e9f3..425f6b4 100644 --- a/sem-v/01_regression/residualSquaredLoss.py +++ b/sem-v/01_regression/residualSquaredLoss.py @@ -1,23 +1,24 @@ """ - y_hat is prediction done by our algorithm, it is defined as: - - y_hat = (w.phi(x)) - - # Losses: Measures how wrong predictor predicts - In our course, we took Residual but in ML approach they call it as error (i.e., in prediction) +y_hat is prediction done by our algorithm, it is defined as: - Residual = (y_hat - true_y) # statistical - Error = (true_y - y_hat) # ML approach + y_hat = (w.phi(x)) - SquaredLoss: Used in linear regression to flip the sings and there are other advantages too +# Losses: Measures how wrong predictor predicts + In our course, we took Residual but in ML approach they call it as error (i.e., in prediction) - SquaredLoss = (Residual)^2 or (y_hat - true_y)^2 + Residual = (y_hat - true_y) # statistical + Error = (true_y - y_hat) # ML approach + + SquaredLoss: Used in linear regression to flip the sings and there are other advantages too + + SquaredLoss = (Residual)^2 or (y_hat - true_y)^2 """ -x = [3,4] +x = [3, 4] w = [0.5, -1.5] -true_y = int(input("What's true_y? ")) # get y input +true_y = int(input("What's true_y? ")) # get y input + # find margin/score w.phi(x) where phi(x) = array of x or feature vectors def score(feature_vectors, weights): @@ -27,16 +28,20 @@ def score(feature_vectors, weights): return result + y_hat = score(x, w) + # Find residual def residual(y_hat, true_y): - return (y_hat - true_y) + return y_hat - true_y + # Find Squared Loss def squared_loss(residual): return (residual) ** 2 + # loss computation r = residual(y_hat, true_y) sqLoss = squared_loss(r) diff --git a/sem-v/02_loss_minimization_framework/lmf.py b/sem-v/02_loss_minimization_framework/lmf.py index 7b49fa7..b945868 100644 --- a/sem-v/02_loss_minimization_framework/lmf.py +++ b/sem-v/02_loss_minimization_framework/lmf.py @@ -1,42 +1,39 @@ # lmf = loss minimization framework """ - Previously, we were trying to find losses sample by sample. - Now, by using Loss Minimization Framework (LMF), - we generalize the idea from 1 sample to all training examples. - - TrainLoss(w) = (1/N) ∑ Loss(xᵢ, yᵢ, w) - - where: - N : number of training examples - xᵢ, yᵢ : ith sample and its true label/output - w : weight vector - Loss(xᵢ, yᵢ, w) : Loss on single sample - TrainLoss(w) : average loss over the entire dataset - - In our case (Linear Regression): - - Loss(xᵢ, yᵢ, w) = (y_hat - true_y)^2 - TrainLoss(w) = (1/N) ∑ (y_hatᵢ - yᵢ)^2 +Previously, we were trying to find losses sample by sample. +Now, by using Loss Minimization Framework (LMF), +we generalize the idea from 1 sample to all training examples. + +TrainLoss(w) = (1/N) ∑ Loss(xᵢ, yᵢ, w) + +where: + N : number of training examples + xᵢ, yᵢ : ith sample and its true label/output + w : weight vector + Loss(xᵢ, yᵢ, w) : Loss on single sample + TrainLoss(w) : average loss over the entire dataset + +In our case (Linear Regression): + + Loss(xᵢ, yᵢ, w) = (y_hat - true_y)^2 + TrainLoss(w) = (1/N) ∑ (y_hatᵢ - yᵢ)^2 """ # ------------------------------ Dataset ------------------------------ # Each element = (xᵢ, yᵢ) # xᵢ represents the feature vector, yᵢ is the true output -dataset = [ - ([3, 4], 2), - ([1, -1], -1), - ([2, 3], 4) -] +dataset = [([3, 4], 2), ([1, -1], -1), ([2, 3], 4)] # Initial weights w = [0.5, -1.5] + # ------------------------------ Step 1: Prediction ------------------------------ def score(feature_vectors, weights): """ - Computes: w · φ(x) - where φ(x) = feature vector + Computes: w · φ(x) + where φ(x) = feature vector """ result = 0 for xi, wi in zip(feature_vectors, weights): @@ -47,18 +44,18 @@ def score(feature_vectors, weights): # ------------------------------ Step 2: Per-sample Loss ------------------------------ def squared_loss(y_hat, true_y): """ - Squared Loss = (y_hat - true_y)^2 - Measures how far prediction deviates from actual value + Squared Loss = (y_hat - true_y)^2 + Measures how far prediction deviates from actual value """ residual = y_hat - true_y - return residual ** 2 + return residual**2 # ------------------------------ Step 3: Training Loss ------------------------------ def train_loss(dataset, weights): """ - TrainLoss(w) = (1/N) ∑ (y_hatᵢ - yᵢ)^2 - This generalizes loss to the whole training dataset. + TrainLoss(w) = (1/N) ∑ (y_hatᵢ - yᵢ)^2 + This generalizes loss to the whole training dataset. """ N = len(dataset) total_loss = 0 @@ -67,11 +64,11 @@ def train_loss(dataset, weights): loss_i = squared_loss(y_hat, y_i) total_loss += loss_i print(f"Sample: x={x_i}, y={y_i}, y_hat={y_hat:.3f}, Loss={loss_i:.3f}") - + avg_loss = total_loss / N return avg_loss # ------------------------------ Step 4: Execute ------------------------------ train_loss_value = train_loss(dataset, w) -print(f"\nTrainLoss(w): {train_loss_value:.3f}") \ No newline at end of file +print(f"\nTrainLoss(w): {train_loss_value:.3f}")