Skip to content

Practical Data Science Interview Questions

72 questions with answers. Hands-on questions where you write code, a query, a formula or concrete steps.

How to approach these questions

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.

Solved — practicalStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
02

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
03

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
04

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
05

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
06

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
07

Write Pandas code to read a large CSV in chunks and compute total sales per city.

Save to ▾
Show answer
# process 1 million rows at a time import pandas as pd totals = {} for chunk in pd.read_csv('sales.csv', usecols=['city', 'amount'], chunksize=1_000_000): part = chunk.groupby('city')['amount'].sum() for city, amt in part.items(): totals[city] = totals.get(city, 0) + amt result = pd.Series(totals).sort_values(ascending=False)
08

Write Python code to count word frequencies in a text and print the top 5 words.

Save to ▾
Show answer
from collections import Counter import re def top_words(text, n=5): words = re.findall(r'[a-z]+', text.lower()) return Counter(words).most_common(n) print(top_words('Data science is fun and data is everywhere'))
09

Pandas: compute a 7-day rolling average of daily sales for each store.

Save to ▾
Show answer
# df has columns: store, date, sales df['date'] = pd.to_datetime(df['date']) df = df.sort_values(['store', 'date']) df['sales_7d_avg'] = ( df.groupby('store')['sales'] .transform(lambda s: s.rolling(7, min_periods=1).mean()) )
10

Write a Python function to flatten a nested list of any depth.

Save to ▾
Show answer
def flatten(items): out = [] for x in items: if isinstance(x, list): out.extend(flatten(x)) else: out.append(x) return out print(flatten([1, [2, [3, 4]], 5])) # [1, 2, 3, 4, 5]
11

Pandas: convert wide monthly columns into a long format table.

Save to ▾
Show answer
# wide: id, jan, feb, mar -> long: id, month, value long_df = df.melt( id_vars=['id'], value_vars=['jan', 'feb', 'mar'], var_name='month', value_name='value' )
12

Write Python code to compute a 95% bootstrap confidence interval for the mean.

Save to ▾
Show answer
import numpy as np def bootstrap_ci(x, n_boot=10000, seed=42): rng = np.random.default_rng(seed) x = np.asarray(x) means = [rng.choice(x, size=len(x), replace=True).mean() for _ in range(n_boot)] return np.percentile(means, [2.5, 97.5]) print(bootstrap_ci([12, 15, 9, 20, 14, 11, 18]))
13

How do you check whether a variable is normally distributed?

Save to ▾
Show answer
Start visually with a histogram and a Q-Q plot; points close to the straight line suggest normality. Check skewness and kurtosis values. Then use a formal test such as Shapiro-Wilk for small samples or Anderson-Darling. Remember that with very large samples, tests flag tiny harmless deviations, so judge by the plots too. If data is skewed, consider a log transform or a non-parametric method.
14

Write scikit-learn code for a pipeline with scaling and logistic regression, evaluated with 5-fold cross-validation.

Save to ▾
Show answer
from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)) scores = cross_val_score(pipe, X, y, cv=5, scoring='roc_auc') print(scores.mean(), scores.std())
15

Write scikit-learn code to get precision, recall and a confusion matrix at a custom threshold of 0.3.

Save to ▾
Show answer
from sklearn.metrics import confusion_matrix, precision_score, recall_score proba = model.predict_proba(X_test)[:, 1] pred = (proba >= 0.3).astype(int) print(confusion_matrix(y_test, pred)) print('precision', precision_score(y_test, pred)) print('recall', recall_score(y_test, pred))
16

Write a basic PyTorch training loop for one epoch.

Save to ▾
Show answer
model.train() for X, y in train_loader: X, y = X.to(device), y.to(device) optimizer.zero_grad() logits = model(X) loss = loss_fn(logits, y) loss.backward() optimizer.step() # evaluation model.eval() with torch.no_grad(): val_loss = sum(loss_fn(model(Xv.to(device)), yv.to(device)).item() for Xv, yv in val_loader)
17

Write Keras code for a small binary classifier on tabular data.

Save to ▾
Show answer
from tensorflow import keras model = keras.Sequential([ keras.layers.Input(shape=(X_train.shape[1],)), keras.layers.Dense(64, activation='relu'), keras.layers.Dropout(0.3), keras.layers.Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['AUC']) model.fit(X_train, y_train, validation_split=0.2, epochs=20, batch_size=64)
18

How would you quickly build a sentiment analysis model for product reviews?

Save to ▾
Show answer
Step 1: collect and label a sample of reviews, checking class balance. Step 2: build a baseline with TF-IDF and logistic regression to get a quick benchmark. Step 3: fine-tune a small pretrained transformer such as DistilBERT for better accuracy, or use a multilingual model if reviews mix languages. Step 4: evaluate with F1 per class and read wrong predictions. Step 5: handle sarcasm and neutral reviews explicitly.
19

Write Pandas code to create useful features from a datetime column.

Save to ▾
Show answer
df['ts'] = pd.to_datetime(df['ts']) df['hour'] = df['ts'].dt.hour df['dayofweek'] = df['ts'].dt.dayofweek df['is_weekend'] = df['dayofweek'].isin([5, 6]).astype(int) df['month'] = df['ts'].dt.month df['days_since_signup'] = (df['ts'] - df['signup_date']).dt.days
20

Write Pandas code to create lag and rolling features for each customer.

Save to ▾
Show answer
df = df.sort_values(['customer_id', 'month']) g = df.groupby('customer_id')['spend'] df['spend_lag1'] = g.shift(1) df['spend_lag3'] = g.shift(3) # shift first so the current month is not included df['spend_roll3_mean'] = g.transform(lambda s: s.shift(1).rolling(3).mean())
21

Write a scikit-learn ColumnTransformer that preprocesses numeric and categorical columns.

Save to ▾
Show answer
from sklearn.compose import ColumnTransformer from sklearn.pipeline import make_pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder pre = ColumnTransformer([ ('num', make_pipeline(SimpleImputer(strategy='median'), StandardScaler()), num_cols), ('cat', make_pipeline(SimpleImputer(strategy='most_frequent'), OneHotEncoder(handle_unknown='ignore')), cat_cols) ]) model = make_pipeline(pre, LogisticRegression(max_iter=1000))
22

How would you build RFM features for a customer churn model?

Save to ▾
Show answer
RFM stands for recency, frequency and monetary value. From the transactions table, for each customer as of a cut-off date: recency is days since the last purchase, frequency is the number of orders in the last 90 days, and monetary is total or average spend in that window. Compute them using only data before the cut-off, add trends like spend this month versus last, and the label from the period after.
23

Write Python code to compute the haversine distance between customer and store locations.

Save to ▾
Show answer
import numpy as np def haversine_km(lat1, lon1, lat2, lon2): lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2]) dlat, dlon = lat2 - lat1, lon2 - lon1 a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2) ** 2 return 6371 * 2 * np.arcsin(np.sqrt(a)) df['dist_km'] = haversine_km(df.cust_lat, df.cust_lon, df.store_lat, df.store_lon)
24

Write Pandas code to encode hour of day as a cyclical feature.

Save to ▾
Show answer
import numpy as np # hour 23 and hour 0 should be close, so use sin and cos df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24) df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)
25

Write Pandas code to cap outliers at the 1st and 99th percentile.

Save to ▾
Show answer
# fit limits on training data only, then apply to test low, high = train['income'].quantile([0.01, 0.99]) train['income_capped'] = train['income'].clip(low, high) test['income_capped'] = test['income'].clip(low, high)
26

Write SQL to find the second highest salary in an employees table.

Save to ▾
Show answer
SELECT MAX(salary) AS second_highest FROM employees WHERE salary < (SELECT MAX(salary) FROM employees); -- alternative with window function SELECT DISTINCT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees) t WHERE rnk = 2;
27

Write SQL to find the top 3 products by revenue in each category.

Save to ▾
Show answer
WITH rev AS ( SELECT category, product_id, SUM(price * qty) AS revenue FROM order_items GROUP BY category, product_id ), ranked AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn FROM rev ) SELECT category, product_id, revenue FROM ranked WHERE rn <= 3;
28

Write SQL to compute a 7-day rolling average of daily active users.

Save to ▾
Show answer
WITH daily AS ( SELECT activity_date, COUNT(DISTINCT user_id) AS dau FROM events GROUP BY activity_date ) SELECT activity_date, dau, AVG(dau) OVER (ORDER BY activity_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS dau_7d_avg FROM daily ORDER BY activity_date;
29

Write SQL to calculate month-over-month revenue growth.

Save to ▾
Show answer
WITH monthly AS ( SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue FROM orders GROUP BY 1 ) SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev_revenue, ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month)) / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 2) AS mom_pct FROM monthly;
30

Write SQL to find duplicate emails in a users table.

Save to ▾
Show answer
SELECT email, COUNT(*) AS cnt FROM users GROUP BY email HAVING COUNT(*) > 1 ORDER BY cnt DESC;
31

Write SQL to compute week-1 retention by signup week.

Save to ▾
Show answer
WITH signups AS ( SELECT user_id, DATE_TRUNC('week', signup_date) AS cohort, signup_date FROM users ), active AS ( SELECT DISTINCT s.user_id, s.cohort FROM signups s JOIN events e ON e.user_id = s.user_id AND e.event_date >= s.signup_date + INTERVAL '7 day' AND e.event_date < s.signup_date + INTERVAL '14 day' ) SELECT s.cohort, COUNT(*) AS users, ROUND(100.0 * COUNT(a.user_id) / COUNT(*), 1) AS week1_retention_pct FROM signups s LEFT JOIN active a ON a.user_id = s.user_id GROUP BY s.cohort ORDER BY s.cohort;
32

Write SQL to find customers who ordered in January 2026 but not in February 2026.

Save to ▾
Show answer
SELECT DISTINCT o.customer_id FROM orders o WHERE o.order_date >= '2026-01-01' AND o.order_date < '2026-02-01' AND NOT EXISTS ( SELECT 1 FROM orders f WHERE f.customer_id = o.customer_id AND f.order_date >= '2026-02-01' AND f.order_date < '2026-03-01' );
33

Write SQL to find the median order value per city.

Save to ▾
Show answer
SELECT city, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) AS median_amount FROM orders GROUP BY city; -- PERCENTILE_CONT interpolates; PERCENTILE_DISC returns an actual value
34

Write SQL to pivot order counts by status into columns using CASE WHEN.

Save to ▾
Show answer
SELECT DATE_TRUNC('month', order_date) AS month, SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered, SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled, SUM(CASE WHEN status = 'returned' THEN 1 ELSE 0 END) AS returned FROM orders GROUP BY 1 ORDER BY 1;
35

How do you pull large data from a SQL database into Pandas efficiently?

Save to ▾
Show answer
Push as much work as possible into SQL: filter, aggregate and select only needed columns before pulling. Use pd.read_sql with a SQLAlchemy engine and chunksize to stream large results. For very large extracts, export to Parquet from the warehouse and read that, which is much faster than row-by-row transfer. Set dtypes like category early, and never use SELECT star on a big table from a notebook.
36

Write SQL to compute a running total of spend for each user.

Save to ▾
Show answer
SELECT user_id, order_date, amount, SUM(amount) OVER ( PARTITION BY user_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_spend FROM orders ORDER BY user_id, order_date;
37

Write SQL to compute funnel conversion from visit to cart to purchase.

Save to ▾
Show answer
WITH steps AS ( SELECT user_id, MAX(CASE WHEN event = 'visit' THEN 1 ELSE 0 END) AS visited, MAX(CASE WHEN event = 'add_to_cart' THEN 1 ELSE 0 END) AS carted, MAX(CASE WHEN event = 'purchase' THEN 1 ELSE 0 END) AS purchased FROM events WHERE event_date >= '2026-10-01' GROUP BY user_id ) SELECT SUM(visited) AS visits, SUM(carted) AS carts, SUM(purchased) AS buyers, ROUND(100.0 * SUM(carted) / NULLIF(SUM(visited), 0), 1) AS visit_to_cart_pct, ROUND(100.0 * SUM(purchased) / NULLIF(SUM(carted), 0), 1) AS cart_to_buy_pct FROM steps;
38

Write Python code to find the top 3 most similar documents to a query using cosine similarity on embeddings.

Save to ▾
Show answer
import numpy as np def top_k(query_vec, doc_vecs, k=3): q = query_vec / np.linalg.norm(query_vec) d = doc_vecs / np.linalg.norm(doc_vecs, axis=1, keepdims=True) scores = d @ q idx = np.argsort(-scores)[:k] return list(zip(idx, scores[idx])) # doc_vecs shape: (n_docs, dim), query_vec shape: (dim,)
39

How do you get reliable JSON output from an LLM?

Save to ▾
Show answer
Use the provider's structured output or JSON schema mode when available, which constrains the output to your schema. Otherwise, describe the exact schema in the prompt with an example, and use low temperature. Always parse and validate the response in code, for example with Pydantic, and on failure retry with the error message included. Keep schemas small and flat, and use enums for fields with fixed values.
40

Write a prompt template for classifying customer support tickets.

Save to ▾
Show answer
System: You classify support tickets for an e-commerce company. Categories: payment, delivery, refund, account, other. Rules: choose exactly one category; if unsure, choose other; do not invent details. Return JSON with fields category and reason, reason under 20 words. Then two short examples showing a ticket and the expected JSON. User: Ticket: {ticket_text}. Keep the template fixed and test it on 100 labelled tickets before rollout.
41

Write a FastAPI endpoint that serves predictions from a saved scikit-learn model.

Save to ▾
Show answer
from fastapi import FastAPI from pydantic import BaseModel import joblib import pandas as pd app = FastAPI() model = joblib.load('model.joblib') class Customer(BaseModel): tenure: int monthly_spend: float plan: str @app.post('/predict') def predict(c: Customer): X = pd.DataFrame([c.model_dump()]) return {'churn_probability': float(model.predict_proba(X)[0, 1])}
42

Write a Dockerfile for a Python model API.

Save to ▾
Show answer
FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY app/ ./app COPY model.joblib . EXPOSE 8000 CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
43

Write Python code to compute the Population Stability Index for a feature to detect drift.

Save to ▾
Show answer
import numpy as np def psi(expected, actual, bins=10): edges = np.quantile(expected, np.linspace(0, 1, bins + 1)) edges[0], edges[-1] = -np.inf, np.inf e = np.histogram(expected, edges)[0] / len(expected) a = np.histogram(actual, edges)[0] / len(actual) e, a = np.clip(e, 1e-6, None), np.clip(a, 1e-6, None) return float(np.sum((a - e) * np.log(a / e))) # rule of thumb: <0.1 stable, 0.1-0.25 watch, >0.25 investigate
44

What should you log for a production prediction service?

Save to ▾
Show answer
For each request, log a request ID, timestamp, model version, input features or a hash of them, the prediction and score, and latency. Log errors and fallback use separately. Do not log raw personal data unless needed and allowed; mask it. Aggregate these logs into dashboards for traffic, latency percentiles, error rate and score distribution. Joining logged predictions with later outcomes gives the data for monitoring and retraining.
45

Write pytest unit tests for a feature function that computes days since last purchase.

Save to ▾
Show answer
import pandas as pd from features import days_since_last_purchase def test_basic_case(): df = pd.DataFrame({'customer_id': [1, 1], 'order_date': pd.to_datetime(['2026-01-01', '2026-01-10'])}) out = days_since_last_purchase(df, as_of='2026-01-15') assert out.loc[1] == 5 def test_no_future_orders_used(): df = pd.DataFrame({'customer_id': [1], 'order_date': pd.to_datetime(['2026-02-01'])}) out = days_since_last_purchase(df, as_of='2026-01-15') assert out.empty
46

Write Pandas code to resample daily sales into weekly totals and monthly averages.

Save to ▾
Show answer
import pandas as pd df['date'] = pd.to_datetime(df['date']) s = df.set_index('date')['sales'].sort_index() # Weekly totals, weeks ending on Sunday weekly = s.resample('W-SUN').sum() # Monthly average of daily sales monthly = s.resample('MS').mean() print(weekly.head()) print(monthly.head())
47

Write Python code to decompose a monthly series into trend, seasonal and residual parts with STL.

Save to ▾
Show answer
import pandas as pd from statsmodels.tsa.seasonal import STL s = df.set_index('month')['sales'].asfreq('MS') res = STL(s, period=12, robust=True).fit() parts = pd.DataFrame({ 'trend': res.trend, 'seasonal': res.seasonal, 'resid': res.resid }) print(parts.tail()) res.plot()
48

Write Python code to run an ADF stationarity test and difference the series if needed.

Save to ▾
Show answer
from statsmodels.tsa.stattools import adfuller def is_stationary(s, alpha=0.05): p_value = adfuller(s.dropna())[1] return p_value < alpha series = s.copy() d = 0 while not is_stationary(series) and d < 2: series = series.diff() d += 1 print('differencing order d =', d)
49

Write Python code to evaluate a forecasting model with expanding-window time series cross-validation.

Save to ▾
Show answer
import numpy as np from sklearn.model_selection import TimeSeriesSplit from sklearn.metrics import mean_absolute_error tscv = TimeSeriesSplit(n_splits=5, test_size=28) scores = [] for tr, te in tscv.split(X): model.fit(X.iloc[tr], y.iloc[tr]) pred = model.predict(X.iloc[te]) scores.append(mean_absolute_error(y.iloc[te], pred)) print(np.mean(scores), scores)
50

Write Python code to fit a Holt-Winters model and forecast the next 12 months.

Save to ▾
Show answer
from statsmodels.tsa.holtwinters import ExponentialSmoothing s = df.set_index('month')['sales'].asfreq('MS') train, test = s[:-12], s[-12:] model = ExponentialSmoothing( train, trend='add', seasonal='mul', seasonal_periods=12 ).fit() forecast = model.forecast(12) mae = (forecast - test).abs().mean() print(forecast.round(1), 'MAE:', round(mae, 1))
51

Write a Python function to compute MASE for a seasonal forecast.

Save to ▾
Show answer
import numpy as np def mase(y_train, y_true, y_pred, m=7): # Scale: in-sample error of seasonal naive y_train = np.asarray(y_train) scale = np.mean(np.abs(y_train[m:] - y_train[:-m])) err = np.mean(np.abs(np.asarray(y_true) - np.asarray(y_pred))) return err / scale # MASE below 1 beats seasonal naive
52

Write Python code to group a list of order dictionaries by city and sum the amounts without Pandas.

Save to ▾
Show answer
from collections import defaultdict orders = [ {'city': 'Pune', 'amount': 250}, {'city': 'Delhi', 'amount': 400}, {'city': 'Pune', 'amount': 150}, ] totals = defaultdict(float) for o in orders: totals[o['city']] += o['amount'] print(dict(totals)) # {'Pune': 400.0, 'Delhi': 400.0}
53

Pandas: find customers whose monthly spend increased for three consecutive months.

Save to ▾
Show answer
m = (df.assign(month=df['date'].dt.to_period('M')) .groupby(['customer_id', 'month'])['amount'].sum() .reset_index() .sort_values(['customer_id', 'month'])) m['up'] = (m.groupby('customer_id')['amount'].diff() > 0).astype(int) # three rises in a row = three consecutive increases m['streak'] = (m.groupby('customer_id')['up'] .rolling(3).sum().reset_index(level=0, drop=True)) result = m.loc[m['streak'] == 3, 'customer_id'].unique()
54

Write scikit-learn code to calibrate a gradient boosting classifier's probabilities and check the result.

Save to ▾
Show answer
from sklearn.ensemble import HistGradientBoostingClassifier from sklearn.calibration import CalibratedClassifierCV from sklearn.metrics import brier_score_loss base = HistGradientBoostingClassifier() cal = CalibratedClassifierCV(base, method='isotonic', cv=5) cal.fit(X_train, y_train) prob = cal.predict_proba(X_test)[:, 1] print('Brier:', brier_score_loss(y_test, prob))
55

Write OpenCV code to read an image, convert it to grayscale, resize it and detect edges.

Save to ▾
Show answer
import cv2 img = cv2.imread('part.jpg') # loaded as BGR if img is None: raise FileNotFoundError('part.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) small = cv2.resize(gray, (224, 224), interpolation=cv2.INTER_AREA) blur = cv2.GaussianBlur(small, (5, 5), 0) edges = cv2.Canny(blur, 50, 150) cv2.imwrite('edges.png', edges)
56

Write torchvision transforms for training and validation of an image classifier using ImageNet normalisation.

Save to ▾
Show answer
from torchvision import transforms as T mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] train_tf = T.Compose([ T.RandomResizedCrop(224), T.RandomHorizontalFlip(), T.ColorJitter(0.2, 0.2, 0.2), T.ToTensor(), T.Normalize(mean, std), ]) val_tf = T.Compose([ T.Resize(256), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean, std), ])
57

Write a Python function to compute IoU between two bounding boxes given as (x1, y1, x2, y2).

Save to ▾
Show answer
def iou(a, b): ix1, iy1 = max(a[0], b[0]), max(a[1], b[1]) ix2, iy2 = min(a[2], b[2]), min(a[3], b[3]) inter = max(0, ix2 - ix1) * max(0, iy2 - iy1) area_a = (a[2] - a[0]) * (a[3] - a[1]) area_b = (b[2] - b[0]) * (b[3] - b[1]) union = area_a + area_b - inter return inter / union if union > 0 else 0.0 print(iou((0, 0, 10, 10), (5, 5, 15, 15))) # 0.142...
58

Write PyTorch code to fine-tune a pretrained ResNet-18 for a 5-class problem by replacing its final layer.

Save to ▾
Show answer
import torch, torch.nn as nn from torchvision import models model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT) for p in model.parameters(): p.requires_grad = False # freeze backbone model.fc = nn.Linear(model.fc.in_features, 5) opt = torch.optim.AdamW(model.fc.parameters(), lr=1e-3) loss_fn = nn.CrossEntropyLoss() # train head first, then unfreeze later layers with a lower lr
59

Write NumPy code to compute the Dice coefficient between a predicted and a true binary mask.

Save to ▾
Show answer
import numpy as np def dice(pred, true, eps=1e-7): pred = pred.astype(bool) true = true.astype(bool) inter = np.logical_and(pred, true).sum() return (2 * inter + eps) / (pred.sum() + true.sum() + eps) # Dice = 2|A and B| / (|A| + |B|); 1 means perfect overlap
60

Write NumPy code for non-maximum suppression on a set of boxes and scores.

Save to ▾
Show answer
import numpy as np def nms(boxes, scores, thr=0.5): x1, y1, x2, y2 = boxes.T areas = (x2 - x1) * (y2 - y1) order = scores.argsort()[::-1] keep = [] while order.size: i = order[0] keep.append(i) w = np.maximum(0, np.minimum(x2[i], x2[order[1:]]) - np.maximum(x1[i], x1[order[1:]])) h = np.maximum(0, np.minimum(y2[i], y2[order[1:]]) - np.maximum(y1[i], y1[order[1:]])) inter = w * h iou = inter / (areas[i] + areas[order[1:]] - inter) order = order[1:][iou < thr] return keep
61

Write Python code using Hugging Face transformers to run sentiment analysis on a list of reviews.

Save to ▾
Show answer
from transformers import pipeline clf = pipeline( 'sentiment-analysis', model='distilbert-base-uncased-finetuned-sst-2-english' ) reviews = ['Delivery was fast and the product is great', 'Packaging was damaged and support did not reply'] for text, out in zip(reviews, clf(reviews, batch_size=16)): print(out['label'], round(out['score'], 3), '-', text)
62

Write SQL to find users who logged in on at least three consecutive days.

Save to ▾
Show answer
WITH d AS ( SELECT DISTINCT user_id, CAST(login_at AS DATE) AS day FROM logins ), g AS ( SELECT user_id, day, day - CAST(ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS INT) AS grp FROM d ) SELECT DISTINCT user_id FROM g GROUP BY user_id, grp HAVING COUNT(*) >= 3; -- date minus row number is constant within a streak (PostgreSQL syntax)
63

Write SQL to show each customer's first order date, last order date and the gap between them in days.

Save to ▾
Show answer
SELECT customer_id, MIN(order_date) AS first_order, MAX(order_date) AS last_order, MAX(order_date) - MIN(order_date) AS days_between, COUNT(*) AS orders FROM orders GROUP BY customer_id ORDER BY days_between DESC; -- PostgreSQL: DATE minus DATE gives days; use DATEDIFF in other engines
64

Write Python code for a two-proportion z-test comparing conversion between control and treatment.

Save to ▾
Show answer
from statsmodels.stats.proportion import proportions_ztest, proportion_confint conversions = [480, 540] # control, treatment visitors = [10000, 10000] z, p = proportions_ztest(conversions, visitors) lift = conversions[1] / visitors[1] - conversions[0] / visitors[0] ci_t = proportion_confint(conversions[1], visitors[1], method='wilson') print(f'z={z:.2f} p={p:.4f} abs lift={lift:.4f} treatment CI={ci_t}')
65

Write SQL to compute users, conversions and conversion rate for each experiment variant.

Save to ▾
Show answer
SELECT a.variant, COUNT(DISTINCT a.user_id) AS users, COUNT(DISTINCT o.user_id) AS converters, ROUND(COUNT(DISTINCT o.user_id) * 1.0 / COUNT(DISTINCT a.user_id), 4) AS conv_rate FROM assignments a LEFT JOIN orders o ON o.user_id = a.user_id AND o.created_at >= a.assigned_at WHERE a.experiment_id = 'checkout_v2' GROUP BY a.variant;
66

Write Python code to calculate the sample size per group needed to detect a lift from 5 percent to 5.5 percent conversion.

Save to ▾
Show answer
from statsmodels.stats.power import NormalIndPower from statsmodels.stats.proportion import proportion_effectsize baseline, target = 0.05, 0.055 effect = proportion_effectsize(target, baseline) # Cohen's h n = NormalIndPower().solve_power( effect_size=effect, alpha=0.05, power=0.8, ratio=1.0, alternative='two-sided' ) print(round(n)) # about 31,000 users per group
67

Write a Python function that deterministically assigns users to experiment variants using hashing.

Save to ▾
Show answer
import hashlib def assign(user_id, experiment, variants=('control', 'treatment'), weights=(50, 50)): key = f'{experiment}:{user_id}'.encode() bucket = int(hashlib.sha256(key).hexdigest(), 16) % 100 cumulative = 0 for v, w in zip(variants, weights): cumulative += w if bucket < cumulative: return v # Same user + experiment always gets the same variant; # salting with the experiment name keeps tests independent
68

Write Python code to compare revenue per user between two groups using Welch's t-test.

Save to ▾
Show answer
import numpy as np from scipy import stats ctrl = df.loc[df.variant == 'control', 'revenue'].to_numpy() treat = df.loc[df.variant == 'treatment', 'revenue'].to_numpy() t, p = stats.ttest_ind(treat, ctrl, equal_var=False) # Welch diff = treat.mean() - ctrl.mean() se = np.sqrt(treat.var(ddof=1) / len(treat) + ctrl.var(ddof=1) / len(ctrl)) print(f'diff={diff:.2f} 95% CI=({diff - 1.96*se:.2f}, {diff + 1.96*se:.2f}) p={p:.4f}')
69

Write Python code to apply a CUPED adjustment using each user's pre-experiment metric.

Save to ▾
Show answer
import numpy as np # df has: variant, y (metric during test), x (same metric pre-test) x, y = df['x'].to_numpy(), df['y'].to_numpy() theta = np.cov(x, y, ddof=1)[0, 1] / np.var(x, ddof=1) df['y_cuped'] = y - theta * (x - x.mean()) print(df.groupby('variant')[['y', 'y_cuped']].agg(['mean', 'var'])) # Means stay comparable; variance of y_cuped is lower
70

Write a Python function to split a long text into overlapping chunks by word count for a RAG index.

Save to ▾
Show answer
def chunk_words(text, size=200, overlap=40): if overlap >= size: raise ValueError('overlap must be smaller than size') words = text.split() chunks, step = [], size - overlap for start in range(0, len(words), step): chunks.append(' '.join(words[start:start + size])) if start + size >= len(words): break return chunks print(len(chunk_words(doc_text)))
71

Write Pandas code to compute each customer's average order value excluding the current order.

Save to ▾
Show answer
g = df.groupby('customer_id')['amount'] total = g.transform('sum') count = g.transform('count') # Leave-one-out mean; NaN when it is the customer's only order df['avg_other_orders'] = (total - df['amount']) / (count - 1) df.loc[count == 1, 'avg_other_orders'] = float('nan') # For time-aware features, use only earlier orders instead
72

Write Python code that validates prediction requests with Pydantic before passing them to a model.

Save to ▾
Show answer
from pydantic import BaseModel, Field, ValidationError class LoanRequest(BaseModel): age: int = Field(ge=18, le=100) income: float = Field(gt=0) city: str = Field(min_length=2) def predict(payload: dict): try: req = LoanRequest(**payload) except ValidationError as e: return {'error': e.errors()} return {'score': float(model.predict_proba([[req.age, req.income]])[0, 1])}

Frequently asked questions

Why are practical questions important?

Most technical rounds include at least one live task. Practising the exact typing and reasoning makes you calm and fast in the real round.

How should I answer them?

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.