Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""Advanced capstone: Tkinter app with three ML windows."""

from __future__ import annotations

from pathlib import Path
import numpy as np
import pandas as pd

from sklearn.metrics import mean_squared_error

ASSETS = Path(__file__).resolve().parent.parent / "assets"


def quick_shape(df: pd.DataFrame) -> tuple[int, int]:
"""Return (rows, columns)."""
return (len(df), len(df.columns))


def regression_rmse(y_true, y_pred) -> float:
"""Return RMSE for regression predictions."""
return np.sqrt(mean_squared_error(y_true, y_pred))
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Practice feature engineering workflow with pandas."""

from __future__ import annotations

from pathlib import Path
import numpy as np
import pandas as pd

ASSETS = Path(__file__).resolve().parent.parent / "assets"
DEFAULT_PATH = ASSETS / "ml_classification.csv"


def load_or_create_dataset(path: str = str(DEFAULT_PATH), n_rows: int = 250) -> pd.DataFrame:

file = Path(path)

if file.exists():
df = pd.read_csv(file)

else:
rng = np.random.default_rng(7)

df = pd.DataFrame({
"age": rng.integers(21, 60, size=n_rows),
"income": rng.normal(85000, 20000, size=n_rows).round(2),
"experience_years": rng.integers(0, 20, size=n_rows),
"city": rng.choice(["Delhi", "Pune", "Chennai", "Kolkata"], size=n_rows),
"education": rng.choice(["UG", "PG", "PhD"], size=n_rows),
})

return df
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""Practice NumPy linear algebra routines."""

from __future__ import annotations
import numpy as np


def eigen_decomposition(A):
"""Return eigenvalues and eigenvectors."""
arr = np.array(A, dtype=float)
vals, vecs = np.linalg.eig(arr)
return vals, vecs


def solve_linear_system(A, b):
"""Solve Ax = b."""
arr = np.array(A, dtype=float)
vec = np.array(b, dtype=float)
return np.linalg.solve(arr, vec)
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Practice Matplotlib plotting patterns."""

from __future__ import annotations
import numpy as np
import matplotlib.pyplot as plt


def generate_data(seed: int = 42, n: int = 120):

rng = np.random.default_rng(seed)

x = np.linspace(0, 10, n)
y = 2.0 * x + rng.normal(0, 2.5, size=n)

return x, y


def line_and_scatter(ax, x, y):

ax.plot(x, y, color="steelblue", linewidth=2, label="line")

ax.scatter(x, y, s=18, color="tomato", alpha=0.7, label="points")

ax.set_title("Line + Scatter")
ax.set_xlabel("x")
ax.set_ylabel("y")

ax.legend()
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Practice NumPy operations."""

from __future__ import annotations
import numpy as np


def make_basic_arrays():

arr_1d = np.array([1, 2, 3, 4, 5], dtype=float)

arr_2d = np.array([[1, 2, 3], [4, 5, 6]], dtype=float)

zeros = np.zeros((2, 3))

ones = np.ones((2, 3))

eye = np.eye(3)

seq = np.arange(1, 10, 2)

return {
"arr_1d": arr_1d,
"arr_2d": arr_2d,
"zeros": zeros,
"ones": ones,
"eye": eye,
"seq": seq,
}


def describe_array(a):

arr = np.array(a)

return {
"shape": arr.shape,
"ndim": arr.ndim,
"size": arr.size,
"dtype": str(arr.dtype),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""Practice pandas operations."""

from __future__ import annotations

from pathlib import Path
import numpy as np
import pandas as pd


ASSETS = Path(__file__).resolve().parent.parent / "assets"
DEFAULT_PATH = ASSETS / "students.csv"


def load_dataset(path: str = str(DEFAULT_PATH)) -> pd.DataFrame:

file = Path(path)

if file.exists():
df = pd.read_csv(file)

else:

rng = np.random.default_rng(42)

df = pd.DataFrame({
"student_id": [f"S{i:03d}" for i in range(1, 13)],
"name": [f"Student{i}" for i in range(1, 13)],
"department": rng.choice(["CSE", "ECE", "ME"], size=12),
"score": rng.integers(55, 100, size=12),
"attendance": rng.integers(65, 100, size=12),
"grade": rng.choice(["A", "B", "C", "D"], size=12)
})

return df
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Practice sklearn pipelines."""

from __future__ import annotations

import numpy as np
import pandas as pd

from sklearn.datasets import make_regression


def make_regression_dataframe(n_samples: int = 500, random_state: int = 42) -> pd.DataFrame:

X, y = make_regression(
n_samples=n_samples,
n_features=4,
noise=15.0,
random_state=random_state
)

df = pd.DataFrame(X, columns=["x1", "x2", "x3", "x4"])

df["region"] = np.where(df["x1"] > 0, "north", "south")

df["segment"] = np.where(df["x2"] > 0.5, "premium", "standard")

df["y"] = y

return df
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
expr = input("Enter arithmetic expression: ")

try:
result = eval(expr)
print(f"Output: {result}")
except Exception as e:
print("Invalid expression")
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
age = int(input("Enter age: "))

if age < 18:
print("Underage")
elif age < 60:
print("Normal citizen")
else:
print("Senior citizen")

day = int(input("Enter the day number: "))

print("Today is: ", end="")

match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
case _:
print("Invalid day")

try:
print(1/0)
except Exception:
print("An error occurred")
finally:
print("Program finished")
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
print("Hello World")
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
integer = int(input("Enter an integer: "))
print(type(integer))

number = float(input("Enter a number (floating point allowed): "))
print(type(number))

array = list(map(int, input("Enter an array of numbers: ").split()))
print(type(array))

nums = [1,2,3,4]
print(",".join(map(str, nums)))

name = input("Enter your name: ")
print(f"Hello, {name}")

x, y, z = 67, 420, 9000
print(x, y, z, sep="\n\n")
19 changes: 19 additions & 0 deletions SOLUTIONS/sanskarcoder29_solutions/test_playground/basics/loops.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
for i in range(5, 101, 5):
print(i, end=" ")

print()

names = ["Avanish","Awwab","Nathan"]
nicknames = ["Amar","Akbar","Anthony"]
hobbies = ["Marvel","Anime","Games"]

for name, nickname in zip(names, nicknames):
print(f"Name: {name}, Nickname: {nickname}")

for name, nickname, hobby in zip(names, nicknames, hobbies):
print(f"Name: {name}, Nickname: {nickname}, Hobby: {hobby}")

choice = 'y'

while choice.lower() == 'y':
choice = input("Enter choice [y/n] : ")
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
a = 5
b = 3

print("AND operator:", a & b)
print("OR operator:", a | b)
print("XOR operator:", a ^ b)
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""Practice shopping cart flow with Tkinter UI."""

from pathlib import Path
import csv
import json
from typing import Any, Dict, List

ASSETS = Path(__file__).resolve().parent.parent / "assets"
ASSETS.mkdir(parents=True, exist_ok=True)
BILLS_CSV = ASSETS / "bills.csv"

PRODUCTS = {
1: {"name": "Notebook", "price": 45.0},
2: {"name": "Pen Pack", "price": 20.0},
3: {"name": "Backpack", "price": 950.0},
4: {"name": "Bottle", "price": 300.0},
}

def compute_tax(total: float, rate: float = 0.18) -> float:
return total * rate

def normalize_user_id(user_id: str) -> str:
return user_id.strip().lower()
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Practice simple classes and methods."""

class Rectangle:

def __init__(self, width: float, height: float):
self.width = width
self.height = height

def area(self) -> float:
return self.width * self.height

def perimeter(self) -> float:
return 2 * (self.width + self.height)


class BankAccount:

def __init__(self, owner: str, balance: float = 0.0):
self.owner = owner
self.balance = balance

def deposit(self, amount: float) -> float:
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
return self.balance

def withdraw(self, amount: float) -> float:
if amount <= 0:
raise ValueError("amount must be positive")
if amount > self.balance:
raise ValueError("insufficient balance")

self.balance -= amount
return self.balance
Loading
Loading