Q1. Scenario: Design a simple class `DataPoint` with attributes x and y. Create an instance with x=3, y=5. Add a method to compute Euclidean distance from origin.
class DataPoint: def __init__(self,x,y): self.x=x; self.y=y; def distance_from_origin(self): return (self.x**2+self.y**2)**0.5. point = DataPoint(3,5); point.distance_from_origin() returns 5.83. This models a data point as an object.
Q2. Scenario: Create a `Model` class with attributes `weights` (list) and `bias`. Include a method `predict` that computes linear combination of input features. Initialize with random weights.
class Model: def __init__(self, n_features): import random; self.weights = [random.random() for _ in range(n_features)]; self.bias = 0; def predict(self, x): return sum(w*xi for w,xi in zip(self.weights, x)) + self.bias. This is a linear model.
Q3. Scenario: Add a method to the `Model` class to update weights using gradient descent (simple update: subtract learning_rate * gradient). Assume you have a gradient list.
def update(self, gradients, lr=0.01): for i in range(len(self.weights)): self.weights[i] -= lr * gradients[i]; self.bias -= lr * gradients[-1] (if bias gradient given). This encapsulates parameter update logic, core to training neural networks.
Q4. Scenario: Create a class `Dataset` that takes a list of samples (each a tuple of features and label) and provides a method to get batch of size batch_size. Use yield to make it iterable.
class Dataset: def __init__(self, data): self.data = data; def batch(self, batch_size): for i in range(0, len(self.data), batch_size): yield self.data[i:i+batch_size]. This allows efficient data loading during training.
Q5. Scenario: Define a class `Polynomial` that takes coefficients as list (e.g., [a,b,c] for ax^2+bx+c). Implement __call__ method to evaluate polynomial at a given x. Test with coeffs [1, -2, 1] at x=2.
class Polynomial: def __init__(self, coeffs): self.coeffs = coeffs; def __call__(self, x): return sum(c * (x**i) for i, c in enumerate(self.coeffs)). For [1,-2,1] (constant, then x, then x^2), at x=2: 1 + (-2*2) + (1*4)=1-4+4=1. __call__ makes instance callable like a function.
