Python Developer (AI/ML) fresher role
1. Python Programming (Core)
1. Q: What are Python’s key features?
A: Python is interpreted, dynamically typed, supports object-oriented programming, has extensive standard
libraries, and emphasizes readability and simplicity.
2. Q: Difference between lists and tuples?
A: Lists are mutable, tuples are immutable; lists use [], tuples use (). Tuples are faster for read-only operations.
3. Q: Explain Python decorators.
A: Decorators are functions that modify other functions without changing their code. Example: @staticmethod or
custom decorators using def wrapper(func): ....
4. Q: Difference between deepcopy and shallow copy?
A: Shallow copy copies the object but references nested objects; deepcopy copies the object and all nested objects
recursively.
5. Q: How does Python handle memory management?
A: Python uses reference counting and a garbage collector for cyclic references to manage memory automatically.
6. Q: Explain Python’s GIL.
A: Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time, limiting true
parallelism in CPU-bound threads.
7. Q: How do you handle exceptions in Python?
A: Using try-except blocks. Optionally, finally for cleanup and else for code when no exception occurs.
8. Q: Difference between Python is and ==?
A: is checks object identity (memory location), == checks value equality.
9. Q: What are Python generators?
A: Generators yield items one at a time using yield, saving memory for large sequences.
10. Q: Explain list comprehensions.
A: Compact syntax to create lists: [x**2 for x in range(10) if x%2==0].
2. AI/ML Fundamentals
1. Q: Difference between supervised and unsupervised learning?
A: Supervised uses labeled data; unsupervised finds patterns in unlabeled data.
2. Q: What is overfitting and how do you prevent it?
A: Overfitting occurs when a model fits training data too closely. Prevent using regularization, dropout, or more
data.
3. Q: Explain Isolation Forest.
A: An unsupervised algorithm for anomaly detection; it isolates anomalies via random partitioning of data.
4. Q: How does a CNN work?
A: Convolutional layers extract spatial features, pooling layers reduce dimensionality, and fully connected layers
classify features.
5. Q: Difference between RNN and LSTM?
A: RNNs suffer from vanishing gradients; LSTM adds gates to maintain long-term dependencies.
6. Q: What is Autoencoder?
A: Neural network used for unsupervised feature learning and anomaly detection; compresses input into latent
space and reconstructs output.
7. Q: How do you evaluate a classification model?
A: Using metrics like accuracy, precision, recall, F1-score, and confusion matrix.
8. Q: Explain the train-test split.
A: Splitting data into training (to train model) and testing (to evaluate model performance) sets.
9. Q: Difference between regression and classification?
A: Regression predicts continuous values, classification predicts discrete labels.
10. Q: How do you detect anomalies in time-series data?
A: Using statistical methods, isolation forests, autoencoders, or LSTM-based prediction errors.
3. Data Analysis / Preprocessing
1. Q: How do you handle missing values?
A: Drop rows/columns, impute with mean/median/mode, or use predictive models.
2. Q: Explain one-hot encoding.
A: Converts categorical values into binary columns for ML models.
3. Q: How do you normalize or standardize data?
A: Normalization scales data between 0–1; standardization converts to zero mean and unit variance.
4. Q: What is feature engineering?
A: Creating new features or transforming existing ones to improve model performance.
5. Q: How do you detect outliers?
A: Using IQR, Z-score, boxplots, or ML algorithms like Isolation Forest.
6. Q: Difference between NumPy array and Python list?
A: NumPy arrays are homogeneous, support vectorized operations, and are memory efficient.
7. Q: How do you merge/join datasets in Pandas?
A: Using merge(), concat(), join() based on keys or indexes.
8. Q: How to handle categorical data in ML?
A: Encoding: one-hot, label encoding, target encoding.
9. Q: Explain rolling/window functions in Pandas.
A: Used for moving averages, sums, or custom operations over time-series windows.
10. Q: How do you visualize data distributions?
A: Using histograms, boxplots, KDE plots with Matplotlib/Seaborn/Plotly.
4. Projects / Practical Knowledge
1. Q: Explain your CCTV optimization project.
A: I preprocessed CCTV footage, applied YOLOv4 for object detection, used Deep SORT for tracking, and applied
CNN anomaly detection to select key frames, reducing storage.
2. Q: How did you integrate GenAI in the CCTV project?
A: Used LangChain and GPT/Claude LLMs to query surveillance events via natural language interface.
3. Q: Challenges faced in lane detection project?
A: Handling shadows, varying lighting, occlusions; solved using Hough transform, edge detection, and robust
preprocessing.
4. Q: Which metrics did you use to evaluate anomaly detection?
A: Precision, recall, F1-score, and detection accuracy on known anomalies.
5. Q: How did you optimize data pipelines?
A: Vectorized operations with NumPy/Pandas, avoided loops, used batch processing for large video frames.
6. Q: How did you handle imbalanced data?
A: Oversampling, undersampling, or using anomaly detection algorithms suited for rare events.
7. Q: Which deep learning frameworks did you use?
A: TensorFlow, Keras, PyTorch for Autoencoders, CNNs, and anomaly detection.
8. Q: How do you deploy models in production?
A: Using Flask APIs, saving model artifacts, handling inference requests.
9. Q: How did you evaluate YOLOv4 performance?
A: Using mAP (mean Average Precision) and tracking consistency across frames.
10. Q: How did you handle real-time video data?
A: Batch processing, streaming frames with OpenCV, reducing computational load with frame skipping and anomaly
selection.
5. Cloud / Deployment
1. Q: How do you deploy a Python ML model?
A: Save model using Pickle or joblib, create a REST API using Flask, handle requests and return predictions.
2. Q: How do you scale ML apps in the cloud?
A: Use AWS services (EC2, Lambda), containerization (Docker), and auto-scaling for load management.
3. Q: What is AWS S3 used for?
A: Storing large datasets, model artifacts, and outputs securely with high availability.
4. Q: Difference between AWS EC2 and Lambda?
A: EC2 provides virtual machines; Lambda is serverless, runs code on demand.
5. Q: How do you secure ML models on cloud?
A: IAM policies, encryption at rest and transit, access control, and API authentication.
6. Q: Explain how to integrate a model with a Flask API.
A: Load model on server start, define routes for prediction, process input, return JSON responses.
7. Q: What’s the benefit of containerization?
A: Ensures consistency across environments, easier deployment, and scalability.
8. Q: How do you handle large datasets in AWS?
A: Use S3 for storage, EC2 or SageMaker for processing, batch or stream processing depending on need.
9. Q: What is inference latency and why does it matter?
A: Time taken for model to return predictions; affects real-time systems like CCTV monitoring.
10. Q: How do you monitor deployed ML models?
A: Logging predictions, tracking performance metrics, retraining if model drifts.
6. AI/ML Tools / Libraries
1. Q: Why use OpenCV?
A: For image/video processing, object detection, feature extraction, and computer vision tasks.
2. Q: Difference between TensorFlow and PyTorch?
A: Tensor
Flow uses static graphs (eager execution optional), PyTorch uses dynamic graphs; PyTorch is more Pythonic and flexible for
research.
3. Q: What is scikit-learn used for?
A: Traditional ML algorithms, preprocessing, model evaluation, and pipeline creation.
4. Q: What is LangChain?
A: Python framework to build LLM-powered applications with prompts, chains, and agents.
5. Q: How do you perform data augmentation?
A: Rotate, flip, crop, add noise, scale images to increase dataset diversity.
6. Q: Why use YOLOv4?
A: Real-time object detection with high accuracy and speed.
7. Q: What is Deep SORT?
A: Tracking algorithm combining Kalman filters and appearance descriptors for multi-object tracking.
8. Q: Difference between TensorFlow and Keras?
A: Keras is high-level API for building neural networks; TensorFlow is the backend engine.
9. Q: How do you use Pandas for large datasets?
A: Chunking, vectorized operations, memory optimization, and efficient file formats (Parquet/Feather).
10. Q: How do you visualize anomalies in Python?
A: Use Matplotlib/Seaborn to plot trends, scatter plots, heatmaps, or dashboard visualization with Plotly/Power BI.
ALL possible coding questions with answers:
1. Python Basics (10 Q&A)
Q1: Reverse a string in Python.
A1:
s = "V2Soft"
reversed_s = s[::-1]
print(reversed_s) # tofs2V
Q2: Check if a number is prime.
A2:
def is_prime(n):
if n <= 1: return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(is_prime(17)) # True
Q3: Count frequency of elements in a list.
A3:
from collections import Counter
lst = [1,2,2,3,3,3]
print(Counter(lst)) # {1:1, 2:2, 3:3}
Q4: Swap two variables without a temp variable.
A4:
a, b = 5, 10
a, b = b, a
print(a, b) # 10 5
Q5: Find the largest number in a list.
A5:
lst = [3,9,1,7]
print(max(lst)) # 9
Q6: List comprehension: squares of even numbers from 1-10.
A6:
squares = [x**2 for x in range(1,11) if x%2==0]
print(squares) # [4,16,36,64,100]
Q7: Merge two dictionaries.
A7:
d1 = {'a':1}; d2={'b':2}
merged = {**d1, **d2}
print(merged) # {'a':1,'b':2}
Q8: Flatten a nested list.
A8:
lst = [[1,2],[3,4]]
flat = [item for sub in lst for item in sub]
print(flat) # [1,2,3,4]
Q9: Check if a string is a palindrome.
A9:
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("radar")) # True
Q10: Remove duplicates from a list.
A10:
lst = [1,2,2,3]
unique = list(set(lst))
print(unique) # [1,2,3]
2. Data Structures & Algorithms (10 Q&A)
Q1: Implement a stack using a list.
A1:
stack = []
[Link](1)
[Link](2)
print([Link]()) # 2
Q2: Reverse a linked list (Python example with class).
A2:
class Node:
def __init__(self, val):
[Link] = val
[Link] = None
def reverse(head):
prev, curr = None, head
while curr:
nxt = [Link]
[Link] = prev
prev = curr
curr = nxt
return prev
Q3: Find the middle element of a list.
A3:
lst = [1,2,3,4,5]
middle = lst[len(lst)//2]
print(middle) # 3
Q4: Implement queue using deque.
A4:
from collections import deque
q = deque()
[Link](1)
[Link](2)
print([Link]()) # 1
Q5: Binary search in sorted array.
A5:
def binary_search(arr, target):
l, r = 0, len(arr)-1
while l <= r:
m = (l+r)//2
if arr[m]==target: return m
elif arr[m]<target: l=m+1
else: r=m-1
return -1
print(binary_search([1,3,5,7],5)) # 2
Q6: Merge two sorted lists.
A6:
def merge(a,b):
res=[]
i=j=0
while i<len(a) and j<len(b):
if a[i]<b[j]: [Link](a[i]); i+=1
else: [Link](b[j]); j+=1
[Link](a[i:]); [Link](b[j:])
return res
print(merge([1,3],[2,4])) # [1,2,3,4]
Q7: Find first non-repeating character in string.
A7:
from collections import Counter
s = "swiss"
freq = Counter(s)
for c in s:
if freq[c]==1: print(c); break # w
Q8: Check if brackets are balanced.
A8:
def balanced(s):
stack=[]
d = {'(':')','[':']','{':'}'}
for c in s:
if c in d: [Link](c)
elif not stack or d[[Link]()]!=c: return False
return not stack
print(balanced("({[]})")) # True
Q9: Find kth largest element in list.
A9:
import heapq
lst=[3,2,1,5,6,4]
print([Link](1,lst)[0]) # 6
Q10: Implement simple hash map using dict.
A10:
hm = {}
hm['key'] = 100
print(hm['key']) # 100
3. Data Handling / ML Problems (10 Q&A)
Q1: Load CSV and compute mean of a column.
A1:
import pandas as pd
df = pd.read_csv("[Link]")
print(df['col'].mean())
Q2: Normalize a numpy array.
A2:
import numpy as np
arr = [Link]([1,2,3])
normalized = (arr - [Link]()) / ([Link]() - [Link]())
print(normalized) # [0,0.5,1]
Q3: Handle missing values in pandas.
A3:
[Link]([Link](), inplace=True)
Q4: Split dataset into train/test.
A4:
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
Q5: Fit a linear regression model.
A5:
from sklearn.linear_model import LinearRegression
model = LinearRegression()
[Link](X_train,y_train)
y_pred = [Link](X_test)
Q6: Evaluate model with accuracy.
A6:
from [Link] import accuracy_score
accuracy_score(y_test, y_pred.round())
Q7: One-hot encode categorical variable.
A7:
pd.get_dummies(df['category'])
Q8: Detect outliers using Isolation Forest.
A8:
from [Link] import IsolationForest
iso = IsolationForest(contamination=0.1)
outliers = iso.fit_predict(X)
Q9: Train a simple CNN using Keras.
A9:
from [Link] import Sequential
from [Link] import Conv2D, Flatten, Dense
model = Sequential([
Conv2D(32,(3,3),activation='relu',input_shape=(28,28,1)),
Flatten(),
Dense(10,activation='softmax')
])
[Link]('adam','sparse_categorical_crossentropy',metrics=['accuracy'])
Q10: Load pre-trained YOLOv4 model in Python (OpenCV).
A10:
import cv2
net = [Link]("[Link]","[Link]")