0% found this document useful (0 votes)
1 views54 pages

Python Competency MCQs - Structured Format

The document contains a structured set of multiple-choice questions (MCQs) focusing on core Python and DevOps concepts, covering topics such as DevOps goals, Python libraries, Django features, data structures, and machine learning tools. Each question includes options, the correct answer, and an explanation for clarity. The test is divided into two sets, with the first set containing questions from Q1 to Q50.

Uploaded by

bugbiteashu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views54 pages

Python Competency MCQs - Structured Format

The document contains a structured set of multiple-choice questions (MCQs) focusing on core Python and DevOps concepts, covering topics such as DevOps goals, Python libraries, Django features, data structures, and machine learning tools. Each question includes options, the correct answer, and an explanation for clarity. The test is divided into two sets, with the first set containing questions from Q1 to Q50.

Uploaded by

bugbiteashu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🎓 Python Competency Test - Structured MCQs

SET 1: Core Python & DevOps (Q1-Q50)

Q1. Which of the following is NOT a DevOps goal?

Options:

A) Faster software delivery


B) Improved collaboration
C) Continuous integration
D) Keeping to regular working hours ✅

Answer: D

Explanation: DevOps goals focus on:

Speed (faster delivery)


Quality (automation, testing)
Collaboration (breaking silos)
Continuous improvement

Regular working hours is NOT a DevOps goal. DevOps often requires on-call rotations and flexibility.

Q2. What is the output of the following code?

python

name = input("Enter your input:")


print("Received input is :", name)

Input: Hi there

Answer:

Enter your input: Hi there


Received input is : Hi there
Explanation:

input() reads user input as a string

print() displays the received input

Q3. Kivy GUI library supports which operating systems? (Select all)

Options:

A) Android ✅
B) Windows ✅
C) iOS ✅
D) Linux ✅

Answer: All (A, B, C, D)

Explanation: Kivy is a cross-platform Python framework that supports:

Desktop: Windows, macOS, Linux


Mobile: Android, iOS
Best for touch-based and mobile applications

Q4. Which features are available in Django? (Select all)

Options:

A) Templating system ✅
B) Session, user management, role-based permissions ✅
C) Object Relational Mapping (ORM) ✅
D) Form handling ✅

Answer: All (A, B, C, D)

Explanation: Django is a full-stack web framework with:

Built-in templating engine (DTL)


Authentication system (users, sessions, permissions)
ORM for database operations
Form handling and validation

Q5. The given code implementation represents which data structure?

Answer: Linked List

Explanation: (Based on typical patterns with nodes and pointers/references)

Q6. Which of the following is an incorrect way of creating a tuple?

Options:

A) (1, 2, 3)
B) tuple([1, 2])
C) ("python", "nodeJS")
D) ["python", "nodeJS"] ✅

Answer: D

Explanation:

A, B, C → Valid tuple creation


D → This creates a list, not a tuple
Square brackets [] create lists
Parentheses () create tuples

Q7. Which library is used to connect PostgreSQL with Python?

Answer: psycopg2

Explanation: psycopg2 is the most popular PostgreSQL adapter for Python.

python
import psycopg2
conn = [Link](
host="localhost",
database="mydb",
user="postgres",
password="password"
)

Q8. What are the correct values after execution of the code?

Answer: x[1] = 47, y[1] = 47, w[0] = 53, u[0] = 53

Explanation: (Context needed from original code - likely demonstrates mutable vs immutable behavior)

Q9. What is the output of the following code?

python

print(List1 + List2)

Answer: [10, 30, 40, 1, 2, 3, 4]

Explanation: The + operator concatenates two lists.

python

List1 = [10, 30, 40]


List2 = [1, 2, 3, 4]
print(List1 + List2) # [10, 30, 40, 1, 2, 3, 4]

Q10. What will be the output?

python

print(acc)

Answer: NameError: name 'acc' is not defined

Explanation:
acc is treated as a variable, not a string

Variable is not defined, so Python raises NameError


To print the string "acc", use: print("acc")

Q11. What is the correct syntax to copy one list into another?

Answer: listA = listB[:]

Explanation:

python

listB = [1, 2, 3]
listA = listB[:] # Creates a shallow copy

# Wrong way:
listA = listB # This creates a reference, not a copy

Q12. Which function prints output to the console?

Answer: print

Explanation: print() is the built-in function to display output to the console.

Q13. Which paths are required while setting up PySpark environment? (Select all)

Options:

A) Spark_Home ✅
B) py4j ✅

Answer: A, B

Explanation: Environment variables needed:

SPARK_HOME → Points to Spark installation

PYTHONPATH → Includes py4j (Python-Java bridge)


Q14. Matplotlib contains ______ which acts as a container for plots.

Answer: Figure and axes

Explanation:

python

import [Link] as plt


fig, ax = [Link]() # Figure contains axes

Figure → Top-level container


Axes → Individual plot area

Q15. All subclasses are a subtype in Object-Oriented Programming.

Answer: True ✅

Explanation: In OOP, inheritance creates an "is-a" relationship. Every subclass is a subtype of its parent class.

Q16. How do you access the last element of a list named bikes?

Answer: bikes[-1]

Explanation:

python

bikes = ["Honda", "Yamaha", "Suzuki"]


print(bikes[-1]) # "Suzuki"

Negative indexing: -1 = last, -2 = second-last, etc.

Q17. If the connect() method fails, which exception is returned?

Answer: OperationalError

Explanation: In database connections (e.g., psycopg2, MySQL):

OperationalError → Connection failures, database unreachable


ProgrammingError → SQL syntax errors

IntegrityError → Constraint violations

Q18. Flask application runs on which port by default?

Answer: 5000

Explanation:

python

from flask import Flask


app = Flask(__name__)

if __name__ == "__main__":
[Link]() # Runs on [Link]

Q19. What is the output of the following code?

python

def pyfunc():
print("Hello function")
print(pyfunc)

Answer: <function pyfunc at 0x...>

Explanation:

pyfunc without () → prints function object (memory address)

pyfunc() with () → calls the function and prints "Hello function"

Q20. Which parameter of SparkContext is used to specify cluster URL?

Answer: Master

Explanation:

python
from pyspark import SparkContext
sc = SparkContext(master="local", appName="MyApp")

master="local" → Local mode

master="yarn" → YARN cluster

master="spark://host:port" → Standalone cluster

Q21. What are data instances in Orange? (Select all)

Options:

A) Vectors ✅
B) Vectors accessed through index ✅
C) Vectors accessed through feature name ✅

Answer: A, B, C

Explanation: In Orange:

python

import Orange
data = [Link]("iris")
instance = data[0] # Access by index
value = instance["sepal length"] # Access by feature name

Q22. Which library helps Python work with RDDs?

Answer: pyspark

Explanation:

python

from pyspark import SparkContext


sc = SparkContext("local", "RDD App")
rdd = [Link]([1, 2, 3, 4])
Q23. Which cloud model provides virtual machines, storage, and infrastructure?

Answer: IaaS (Infrastructure as a Service)

Explanation: Cloud service models:

IaaS → VMs, storage, networking (AWS EC2, Azure VMs)


PaaS → Platform for development (Heroku, Google App Engine)
SaaS → Ready-to-use software (Gmail, Salesforce)

Q24. How do NumPy arrays grow in size?

Answer: Fixed size

Explanation: NumPy arrays have fixed size after creation. To resize:

python

import numpy as np
arr = [Link]([1, 2, 3])
# Cannot grow dynamically like lists
# Must create new array with [Link]() or [Link]()

Q25. Ways to access Neo4j through Python are:

Answer: All of the above

Explanation: Multiple libraries available:

neo4j → Official driver

py2neo → High-level library

REST API calls

Q26. SparkContext uses _____ to launch JVM and create JavaSparkContext.

Answer: py4j

Explanation: PySpark architecture:


Python (PySpark) → Py4J → JVM (Spark Core)

Py4J enables Python to communicate with Java/Scala Spark engine.

Q27. Which file is NOT required while reading data through Orange?

Answer: prefix

Explanation: Orange requires:

Data file (.tab, .csv)


Feature names
Feature types

Prefix is NOT required.

Q28. Which SparkContext parameter is used to initialize a new JVM?

Answer: Gateway

Explanation:

python

from pyspark import SparkContext


sc = SparkContext(gateway=gateway_instance)

Gateway parameter manages the JVM connection.

Q29. Which PyAudio methods block execution until completion? (Select all)

Options:

A) [Link]() ✅
B) [Link]() ✅

Answer: A, B

Explanation: Both methods block (synchronous):


python

import pyaudio
[Link](data) # Blocks until data is played
[Link](frames) # Blocks until frames are read

Q30. Which HTTP method is used to create a resource in REST?

Answer: POST (or PUT)

Explanation: REST HTTP methods:

POST → Create new resource


PUT → Update/create resource (idempotent)
GET → Retrieve resource
DELETE → Remove resource

Q31. [Link]() stores array with which extension?

Answer: .npy

Explanation:

python

import numpy as np
arr = [Link]([1, 2, 3])
[Link]("myarray", arr) # Creates [Link]

Q32. DNS server accepting incorrect information is known as:

Answer: DNS spoofing

Explanation: DNS spoofing = DNS cache poisoning

Attacker provides false DNS information


Redirects users to malicious sites
Q33. What does [Link]() compute?

Answer: Length of the longest path from root to leaf

Explanation: (Based on tree height calculation algorithms)

Q34. What is the difference between tuple and list with same elements?

Answer: Tuples consume less memory than lists

Explanation:

python

import sys
lst = [1, 2, 3]
tup = (1, 2, 3)
print([Link](lst)) # 88 bytes
print([Link](tup)) # 72 bytes

Tuples are immutable → less memory overhead.

Q35. NumPy ndarray stores elements in row-major order.

Answer: True ✅

Explanation: NumPy uses row-major (C-style) order by default.

python

arr = [Link]([[1,2,3], [4,5,6]])


# Memory: 1,2,3,4,5,6 (row by row)

Q36. Method used to configure resolution bits in [Link]:

Answer: setResolutionBits()

Explanation:

python
import mraa
aio = [Link](0)
[Link](12) # Set to 12-bit resolution

Q37. Seq2Seq models in TensorFlow are used for:

Answer: All of the above

Explanation: Sequence-to-Sequence models used for:

Machine translation
Text summarization
Chatbots
Speech recognition

Q38. Different ways of building RNN using TensorFlow:

Answer: All of the above

Explanation: TensorFlow provides multiple RNN implementations:

[Link]

[Link]

[Link]

Q39. Which is NOT a communication channel used in web services?

Answer: MIME

Explanation: Web service channels:

HTTP/HTTPS ✅
SOAP ✅
REST ✅
MIME → Content type standard, NOT a communication channel
Q40. Example of a graph generator in NetworkX:

Answer: nx.petersen_graph()

Explanation:

python

import networkx as nx
G = nx.petersen_graph() # Creates Petersen graph

Q41. Each REST resource is identified by a URI.

Answer: True ✅

Explanation: REST principles:

Every resource has unique URI


Example: [Link]

Q42. The most refined and restrictive service model is:

Answer: CaaS (Container as a Service)

Explanation: Service models (most to least restrictive):

CaaS → Containers
PaaS → Platform
IaaS → Infrastructure

Q43. Best description of ValueError:

Answer: Invalid argument given

Explanation:

python
int("abc") # ValueError: invalid literal
float("xyz") # ValueError

Q44. What happens in the following OpenCV code?

cpp

Mat A = imread("[Link]", IMREAD_GRAYSCALE);


Mat B(A);
Mat C = A;

Answer: B and C point to same Mat A with same header

Explanation: OpenCV Mat shallow copy:

B and C share same data with A


Header is copied, but data is shared

Q45. Broadcast variable is cached on _____ machines.

Answer: All

Explanation:

python

broadcast_var = [Link]([1, 2, 3])

Broadcast variables are cached on all worker nodes to avoid sending data repeatedly.

Q46. What does [Link]() do?

Answer: Lists files in current working directory

Explanation:

python
import os
files = [Link]() # Lists current directory
files = [Link]("/path") # Lists specific directory

Q47. What is the output of the following code?

python

float("abc123")

Answer: ValueError

Explanation: Cannot convert non-numeric string to float.

Q48. Python-based machine learning visual tool:

Answer: Orange

Explanation: Orange provides:

Visual workflow builder


Drag-and-drop widgets
Machine learning algorithms

Q49. Which method decides topic of corpus?

Answer: [Link]

Explanation: LDA (Latent Dirichlet Allocation) for topic modeling:

python

from [Link] import LatentDirichletAllocation


lda = LatentDirichletAllocation(n_components=5)
Q50. Classification algorithm in Orange uses: (Select all)

Options:

A) Learners ✅
B) Classifiers ✅

Answer: A, B

Explanation:

python

from [Link] import TreeLearner


learner = TreeLearner() # Creates learner
model = learner(data) # Creates classifier

SET 2: Advanced Python & ML (Q51-Q100)

Q51. PySpark reduce() output:

python

from pyspark import SparkContext


from operator import add
sc = SparkContext("local", "Reduce app")
nums = [Link]([1, 2, 3, 4, 5])
adding = [Link](add)
print("Adding all the elements -> %i" % (adding))

Answer: Adding all the elements -> 15

Explanation: 1 + 2 + 3 + 4 + 5 = 15

Q52. How to decide the topic of the corpus?

Answer: [Link]
Q53. Classification algorithm used in Orange:

Options:

[Link] ✅
[Link] ✅
[Link] ✅

Answer: All

Q54. Which is NOT a way to build environment?

Answer: Web Server

Explanation: Environment building includes:

Virtual Machines ✅
OS & Application Software ✅
Database server ✅
Web Server → Part of application, not environment building

Q55. Distance measure for categorical variables in k-NN:

Answer: [Link].hamming_loss

Explanation: Hamming distance for categorical data:

python

from [Link] import hamming_loss

Q56. Python-based machine learning visual tool:

Answer: Orange

Explanation:

Weka → Java-based
RapidMiner → Commercial
Orange → Python-based ✅

Q57. Difference between tuples and lists (memory):

Answer: Tuples allocate less memory than lists

Q58. Parameter of SparkContext for initializing new JVM:

Answer: Gateway

Q59. Framework NOT used for web development:

Answer: PyFrame

Explanation: Valid frameworks:

Django ✅
Flask ✅
Pyramid ✅
PyFrame → Does not exist ❌

Q60. Standalone WSGI containers:

Answer: Gunicorn

Explanation: WSGI servers:

Gunicorn ✅
uWSGI ✅
Unicorn → Ruby server ❌
Tornado → Web framework, not WSGI ❌
SET 3: Image Processing, NLP & Web (Q61-Q100)

Q61. Can lambda expressions contain statements?

Answer: No ❌

Explanation: Lambda expressions can only contain expressions, NOT statements.

Valid:

python

lambda x: x + 1 # Expression ✅
lambda x: x if x > 0 else -x # Conditional expression ✅

Invalid:

python

lambda x: return x + 1 # ❌ return is a statement


lambda x: print(x) # ❌ print is a statement (Python 2)
lambda x: for i in range(x) # ❌ for is a statement

Q62. findall() in Python:

Answer: Finds all non-overlapping matches in a string

Explanation:

python

import re
text = "I have 2 apples and 10 oranges"
result = [Link](r"\d+", text)
print(result) # ['2', '10']

Key Points:

Returns a list of matches


Part of re module (regular expressions)
Non-overlapping matches only
Q63. GUI in Python - Standard library:

Answer: Tkinter

Explanation:

python

import tkinter as tk
root = [Link]()
[Link]("My GUI")
label = [Link](root, text="Hello, Python GUI!")
[Link]()
[Link]()

Comparison:

Library Built-in Best For

Tkinter ✅ Yes Beginners, exams

PyQt ❌ No Professional apps

Kivy ❌ No Mobile/touch apps

Q64. Jython (J Python):

Answer: Python implementation written in Java

Explanation:

Runs Python code on JVM


Direct access to Java classes
No need for Py4J bridge

python

# Jython example
from [Link] import Date
d = Date()
print(d)
Key Differences:

Jython → Python runs inside JVM


CPython → Standard Python (written in C)
Py4J → Bridge between separate Python & Java processes

Q65. DevOps Goals:

Answer: Speed + Quality + Automation + Collaboration

Core Goals:

1. ⚡ Faster Delivery
2. 🤝 Improved Collaboration
3. 🤖 Automation
4. 📊 High Reliability
5. 🔄 Continuous Feedback
6. 📈 Scalability

NOT a DevOps Goal: Regular 9-5 working hours ❌

Q66. PyNeo4j - Backend protocol:

Answer: Bolt protocol

Explanation:

python
from neo4j import GraphDatabase

driver = [Link](
"bolt://localhost:7687",
auth=("neo4j", "password")
)

with [Link]() as session:


result = [Link]("RETURN 'Hello Neo4j' AS msg")
print([Link]()["msg"])

Libraries:

neo4j → Official driver (Bolt protocol) ✅

py2neo → High-level, easier syntax

Q67. [Link] characteristics:

Answer: JavaScript runtime, non-blocking I/O, event-driven

Key Features:

Built on Chrome's V8 engine


Single-threaded but highly scalable
Asynchronous by default
npm ecosystem

Comparison:

Feature [Link] Python

Language JavaScript Python

I/O Non-blocking Blocking (default)

Best for APIs, real-time Data, ML

Package Manager npm pip


Q68. NumPy deals with:

Answer: Numerical and scientific computing

What NumPy Handles:

Multidimensional arrays (ndarray)


Mathematical operations
Linear algebra
Matrices & vectors
Fast numerical computation

python

import numpy as np
arr = [Link]([1, 2, 3, 4])
print(arr * 2) # [2 4 6 8]

Q69. print() returns:

Answer: None

Explanation:

python

x = print("Hello")
print(x)
# Output:
# Hello
# None

Common Trap:

print() displays output ✅

print() does NOT return the string ❌

Always returns None


Q70. Python features:

Answer: High-level, interpreted, dynamically typed, object-oriented, platform-independent

Main Features:

1. ✅ Simple & Easy to Learn


2. ✅ Interpreted Language
3. ✅ High-Level Language
4. ✅ Dynamically Typed
5. ✅ Object-Oriented
6. ✅ Platform Independent
7. ✅ Large Standard Library
8. ✅ Open Source

Q71. Clone image with mask method:

Answer: [Link]()

Explanation:

python

import cv2
import numpy as np

src = [Link]("[Link]")
dst = [Link]("[Link]")
mask = [Link]("[Link]", 0)
center = (300, 300)

output = [Link](
src, dst, mask, center, cv2.NORMAL_CLONE
)
[Link]("[Link]", output)

Cloning Types:

cv2.NORMAL_CLONE → Normal blending

cv2.MIXED_CLONE → Mixed blending


cv2.MONOCHROME_TRANSFER → Monochrome transfer

Q72. [Link]() file extension:

Answer: .npy

Explanation:

python

import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
[Link]("my_array", arr) # Creates my_array.npy

# Load back
loaded = [Link]("my_array.npy")

Key Points:

Binary format ✅
Preserves shape & datatype ✅
Not human-readable ❌

Q73. New JVM SparkContext parameter:

Answer: master

Explanation:

python

from pyspark import SparkContext


sc = SparkContext(master="local", appName="TestApp")

Common master values:

local → Local JVM

local[*] → Local JVM, all cores

yarn → YARN cluster

spark://host:port → Standalone cluster


Q74. hostname command:

Answer: Displays system's host name

Usage:

bash

hostname # Show hostname


hostname -i # Show IP address
hostname -f # Show FQDN

Q75. Socket definition:

Answer: Endpoint for communication between two programs

Formula: IP Address + Port = Socket

Types:

Type Connection Reliability Use Case

TCP Connection-oriented Reliable HTTP, FTP, SMTP

UDP Connectionless Unreliable Streaming, gaming

Example:

python

import socket
s = [Link]()
[Link](("localhost", 1234))
[Link](b"Hello")

Q76. Scrapy sends emails using:

Answer: SMTP
Explanation:

python

# [Link]
MAIL_HOST = '[Link]'
MAIL_PORT = 587
MAIL_USER = 'your_email@[Link]'
MAIL_PASS = 'password'
MAIL_TLS = True

Usage:

Error notifications
Spider completion alerts
Log reports

Q77. Scrapy uses for configuration:

Answer: Settings object

Explanation: Scrapy uses centralized Settings object, NOT standard constructor.

Examples of settings:

USER_AGENT

DOWNLOAD_DELAY

CONCURRENT_REQUESTS

ITEM_PIPELINES

MAIL_HOST

Q78. Flask characteristics:

Answer: Micro-framework, lightweight, uses WSGI

Why "Micro": No built-in:

Database layer ❌
Authentication ❌
Form validation ❌

You add only what you need ✅

python

from flask import Flask


app = Flask(__name__)

@[Link]("/")
def home():
return "Hello Flask"

if __name__ == "__main__":
[Link]()

Q79. TextBlob API backend:

Answer: NLTK

Explanation: TextBlob is built on top of NLTK.

What TextBlob provides:

Part-of-speech tagging
Tokenization
Noun phrase extraction
Sentiment analysis

python

from textblob import TextBlob


text = TextBlob("Python is amazing!")
print([Link])

Q80. RDD belongs to which library:

Answer: Apache Spark (PySpark in Python)

Explanation:
python

from pyspark import SparkContext


sc = SparkContext("local", "RDD App")
rdd = [Link]([1, 2, 3, 4])

Key Points:

RDD ≠ Python built-in ❌


RDD ≠ NumPy/Pandas ❌
RDD = Spark library ✅

Q81. run() is invoked by:

Answer: start()

Explanation:

python

from threading import Thread

class MyThread(Thread):
def run(self):
print("Thread running")

t = MyThread()
[Link]() # ✅ Invokes run() internally
# [Link]() # ❌ Runs as normal function, no new thread

Flow: start() → run() → thread execution

Q82. Private Docker Registry command:

Answer: docker run registry:2

Complete command:

bash
docker run -d -p 5000:5000 --name my-registry registry:2

Workflow:

Build → Tag → Push → Pull → Deploy

Example:

bash

docker tag myapp:latest localhost:5000/myapp:latest


docker push localhost:5000/myapp:latest
docker pull localhost:5000/myapp:latest

Q83. Docker Registry images directory:

Answer: /var/lib/registry

Explanation:

bash

docker run -d -p 5000:5000 \


-v /my/registry-data:/var/lib/registry \
--name my-registry registry:2

Common Trap:

/var/lib/docker → Docker engine data ❌

/var/lib/registry → Registry image storage ✅

Q84. NumPy dimensions:

Answer: Number of axes (rank), accessed using ndim

Explanation:

python
import numpy as np
a = [Link]([[1, 2, 3], [4, 5, 6]])
print([Link]) #2
print([Link]) # (2, 3)

Types:

Dimension Name Example

0-D Scalar [Link](5)

1-D Vector [1, 2, 3]

2-D Matrix [[1,2],[3,4]]

3-D+ Tensor Images, video

Q85. Main object in NumPy:

Answer: ndarray (N-dimensional array)

Explanation:

python

import numpy as np
a = [Link]([1, 2, 3])
print(type(a)) # <class '[Link]'>

Q86. Complex binary data format module:

Answer: pickle

Explanation:

python
import pickle

data = {"a": 1, "b": 2}

# Write (serialize)
with open("[Link]", "wb") as f:
[Link](data, f)

# Read (deserialize)
with open("[Link]", "rb") as f:
obj = [Link](f)

Other Modules:

marshal → Internal Python objects

shelve → Persistent storage (dictionary-like)

h5py → Scientific data (HDF5)

Q87. Hyperparameter tuning techniques:

Answer: Grid Search, Random Search, Bayesian Optimization

Comparison:

Technique Speed Accuracy Intelligence

Grid Search Slow High Low

Random Search Fast Good Medium

Bayesian Optimization Medium High High

Example:

python
from sklearn.model_selection import RandomizedSearchCV

param_dist = {
'n_estimators': [50, 100, 200],
'max_depth': [10, 20, 30]
}

rand_search = RandomizedSearchCV(clf, param_dist, n_iter=5)


rand_search.fit(X_train, y_train)

Q88. Read data using Pandas:

Answer: read_*() functions

Common Functions:

File Type Function

CSV read_csv()

Excel read_excel()

JSON read_json()

SQL read_sql()

HTML read_html()

SAS read_sas()

Parquet read_parquet()

Q89. Read SAS file in Pandas:

Answer: read_sas()

Explanation:

python
import pandas as pd
df = pd.read_sas("data.sas7bdat")
print([Link]())

Supported formats:

.sas7bdat

.xpt (SAS transport file)

Q90. Python profiler:

Answer: cProfile

Explanation:

python

import cProfile

def test():
total = 0
for i in range(10000):
total += i
return total

[Link]("test()")

What it shows:

Function execution time


Number of calls
Performance bottlenecks

Q91. Profiler data analyzed by:

Answer: pstats

Workflow:
Program → cProfile (collects) → pstats (analyzes)

Example:

python

import cProfile
import pstats

[Link]("my_function()", "[Link]")
stats = [Link]("[Link]")
stats.sort_stats("cumulative").print_stats(10)

Q92. Haar Cascade:

Answer: Machine learning-based object detection method

What it detects:

Faces ✅
Eyes ✅
Cars ✅
Trees ✅

Example:

python
import cv2

face_cascade = [Link](
"haarcascade_frontalface_default.xml"
)

img = [Link]("[Link]")
gray = [Link](img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x,y,w,h) in faces:


[Link](img,(x,y),(x+w,y+h),(255,0,0),2)

Q93. Logistic Regression:

Answer: Classification model using sigmoid function

Formula:

p = 1 / (1 + e^(-z)), z = wX + b

Example:

python

from sklearn.linear_model import LogisticRegression

X = [Link]([[2], [4], [6], [8]])


y = [Link]([0, 0, 1, 1])

model = LogisticRegression()
[Link](X, y)

print([Link]([[5]])) # [1]
print(model.predict_proba([[5]])) # [[0.35 0.65]]

Key Points:

Used for classification, not regression ✅


Outputs probability (0 to 1)
Linear decision boundary

Q94. word_tokenize(mytext):

Answer: Splits text into word tokens (NLTK)

Explanation:

python

from [Link] import word_tokenize

mytext = "Hello, how are you?"


tokens = word_tokenize(mytext)
print(tokens)
# ['Hello', ',', 'how', 'are', 'you', '?']

Key Difference:

split() → Ignores punctuation

word_tokenize() → Keeps punctuation as separate tokens

Q95. Pandas Series with scalar - index:

Answer: Index must be provided

Explanation:

python

import pandas as pd

# ❌ Error - no index
# [Link](10)

# ✅ Valid - index provided


s = [Link](10, index=['a', 'b', 'c'])
print(s)
#a 10
#b 10
#c 10
Reason: Pandas cannot infer length from scalar.

Q96. Create another SparkContext:

Answer: Not allowed (only ONE per JVM)

Explanation:

python

# ❌ Error
sc1 = SparkContext("local", "App1")
sc2 = SparkContext("local", "App2")
# ValueError: Cannot run multiple SparkContexts at once

# ✅ Correct approach
from [Link] import SparkSession
spark = [Link]()
sc = [Link]

Q97. MRAA GPIO write HIGH:

Answer: [Link](1)

Explanation:

python

import mraa

gpio10 = [Link](10)
[Link](mraa.DIR_OUT)
[Link](1) # HIGH
[Link](0) # LOW

Q98. MRAA GPIO instance requires:

Answer: Pin number

Explanation:
python

import mraa
gpio = [Link](10) # 10 = GPIO pin number

Board NOT required → MRAA auto-detects

Q99. [Link]():

Answer: Lists files in directory

Explanation:

python

import os
files = [Link]() # Current directory
files = [Link]("/path/to/dir") # Specific directory

Q100. Regression algorithm in Orange:

Answer: Linear Regression

Other algorithms:

Random Forest Regression


kNN Regression
Support Vector Regression (SVR)
Neural Network Regression

SET 4: Additional Competency Questions (Q101-Q150)

Q101. Python wrapping in OOP:

Answer: Feature names of objects (Encapsulation)

Explanation: Wrapping = Encapsulation

Bundles data and methods together


Controls access to object features
Protects internal state

Q102. NumPy min(axis=1) output:

python

import numpy as np
nparray = [Link]([[1,2,3],[4,5,6],[7,8,9]])
print([Link](axis=1))

Answer: [1 4 7]

Explanation:

axis=1 → Row-wise operation

Minimum of each row: 1, 4, 7

Q103. NumPy max(axis=1) output:

python

nparray = [Link]([[1,2,3],[4,5,6],[7,8,9]])
print([Link](axis=1))

Answer: [3 6 9]

Explanation:

axis=1 → Row-wise

Maximum of each row: 3, 6, 9

Q104. Canvas in Python:

Answer: Widget used to draw graphics

Explanation:
python

import tkinter as tk

root = [Link]()
canvas = [Link](root, width=400, height=300)
[Link]()

# Draw shapes
canvas.create_line(0, 0, 200, 100)
canvas.create_rectangle(50, 25, 150, 75, fill="blue")
canvas.create_oval(100, 100, 200, 200, fill="red")

[Link]()

Uses:

Draw lines, shapes


Display text, images
Create graphics

Q105. Module for OS interaction:

Answer: os module

Explanation:

python

import os
[Link]() # Current directory
[Link]("newfolder") # Create directory
[Link]("[Link]") # Delete file
[Link]() # List files

Q106. Function h(n) returns True when:

python
def h(n):
f=0
for i in range(1, n+1):
if n % i == 0:
f += 1
return (f == 2)

Answer: n is a prime number

Explanation:

Counts factors of n
Prime numbers have exactly 2 factors (1 and itself)
Returns True when f == 2

Q107. NOT true for polymorphism:

Answer: Increases overloaded function definition always

Explanation: Polymorphism:

✅ Feature of OOP
✅ Improves readability
✅ Same functionality, different implementations
❌ Does NOT always increase overloading

Q108. PyMongo retrieve all objects:

Answer: [Link]()

Explanation:

python
from pymongo import MongoClient

client = MongoClient("localhost", 27017)


db = client["mydatabase"]
collection = db["mycollection"]

# Retrieve all documents


all_docs = [Link]()
for doc in all_docs:
print(doc)

Q109. Py2neo run Cypher query:

Answer: [Link]()

Explanation:

python

from py2neo import Graph

graph = Graph("bolt://localhost:7687",
auth=("neo4j", "password"))

result = [Link]("MATCH (n) RETURN n")

Q110. Read integer in Python:

Answer: int(input())

Explanation:

python

# Correct
n = int(input("Enter number: "))

# Incorrect
n = input() # ❌ Returns string
Q111. SitemapSpider crawls by:

Answer: Reading URLs from [Link]

Explanation:

python

from [Link] import SitemapSpider

class MySpider(SitemapSpider):
sitemap_urls = ["[Link]

def parse(self, response):


# Process each URL from sitemap
yield {'url': [Link]}

Q112. PGP (Pretty Good Privacy) used for:

Answer: Email encryption

Explanation: PGP provides:

🔒 Confidentiality (encryption)
✅ Authentication (verify sender)
🛡️ Integrity (prevent tampering)

Q113. Orange datasets wrapped in:

Answer: Table

Explanation:

python

from [Link] import Table

data = Table("iris")
print(data)
Table wraps:

Features (attributes)
Class labels
Meta-information

Q114. GCD function with negative numbers:

Answer: May cause infinite recursion

Explanation:

python

def gcd(m, n):


if m < n:
m, n = n, m
if m % n == 0:
return n
else:
diff = m - n
return gcd(max(n, diff), min(n, diff))

Works: Positive integers ✅ Breaks: Negative integers ❌ (infinite recursion)

Q115. Class inheritance output:

python
class A:
def __init__(self):
self.i = 1
self.j = 5
def display(self):
print(self.i, self.j)

class B(A):
def __init__(self):
super().__init__()
self.i = 2
self.j = 7

c = B()
[Link]()

Answer: 2 7

Explanation:

super().__init__() calls A's constructor

B's __init__ then overwrites values


Final: i=2, j=7

Q116. Full-stack Python framework:

Answer: Django

Explanation:

Framework Type

Django Full-stack ✅

Flask Microframework

FastAPI Microframework

Q117. CSVFeedSpider:
Answer: Iterates rows, sends to parse_row()

Explanation:

python

from [Link] import CSVFeedSpider

class MySpider(CSVFeedSpider):
start_urls = ["[Link]
delimiter = ","

def parse_row(self, response, row):


yield {
'name': row['name'],
'age': row['age']
}

Q118. OpenCV mouse events:

Answer: All - left-click, right-click, position

Explanation:

python

import cv2

def mouse_event(event, x, y, flags, param):


if event == cv2.EVENT_LBUTTONDOWN:
print(f"Left click at ({x}, {y})")
elif event == cv2.EVENT_RBUTTONDOWN:
print(f"Right click at ({x}, {y})")
elif event == cv2.EVENT_MOUSEMOVE:
print(f"Mouse at ({x}, {y})")

[Link]("Window", mouse_event)

Q119. Framework NOT for web development:

Answer: PyFrame (does not exist)


Valid frameworks:

Django ✅
Flask ✅
Pyramid ✅

Q120. Scrapy sends emails using:

Answer: Scrapy settings (MAIL_HOST, MAIL_FROM)

Configuration:

python

# [Link]
MAIL_FROM = 'you@[Link]'
MAIL_HOST = '[Link]'
MAIL_PORT = 587
MAIL_USER = 'username'
MAIL_PASS = 'password'
MAIL_TLS = True

Q121. Inheritance type A→B→C:

Answer: Multilevel inheritance

Explanation:

python

class A:
pass
class B(A): # B inherits A
pass
class C(B): # C inherits B (which inherits A)
pass

Types:

Single: One parent


Multiple: Multiple parents
Multilevel: Chain (A→B→C) ✅

Q122. HTTP method to create resource:

Answer: POST (or PUT)

REST Methods:

POST → Create ✅
PUT → Update/Create (idempotent)
GET → Retrieve
DELETE → Remove

Q123. Database for NLP:

Answer: WordNet

Explanation: WordNet is a lexical database providing:

Synsets (synonym sets)


Definitions
Semantic relations
Example sentences

python

from [Link] import wordnet


synsets = [Link]("good")

Q124. Hyperparameter tuning technique:

Answer: Randomized Search (or Grid Search)

Methods:

python
from sklearn.model_selection import RandomizedSearchCV

param_dist = {
'n_estimators': [50, 100, 200],
'max_depth': [10, 20, 30]
}

rand_search = RandomizedSearchCV(clf, param_dist)

Q125. MRAA Aio resolution method:

Answer: setBit() or setResolutionBits()

Explanation:

python

import mraa
aio = [Link](0)
[Link](12) # Set 12-bit resolution

Q126. word_tokenize() output:

python

from [Link] import word_tokenize


s = "Hello Mr. Adam, how are you?"
print(word_tokenize(s))

Answer:

['Hello', 'Mr.', 'Adam', ',', 'how', 'are', 'you', '?']

Q127. Pandas scalar Series:

Answer: Index must be provided

Correct:
python

s = [Link](5, index=[0,1,2])

Incorrect:

python

s = [Link](5) # ❌ Error

Q128. CountVectorizer output:

python

corpus = [
"Apple Orange Orange Apple",
"Apple Banana Apple Banana",
"Banana Apple Banana Banana Banana Apple",
"Banana Orange Banana Banana Orange Banana",
"Banana Apple Banana Banana Orange Banana"
]

vectorizer = CountVectorizer()
[Link](corpus)
corpus_vec = [Link](corpus).toarray()

Answer:

[[2 0 2]
[2 2 0]
[2 4 0]
[0 4 2]
[1 4 1]]

Columns: [apple, banana, orange]

Q129. PySpark count() output:

python
words = [Link]([
"Hadoop",
"spark",
"spark vs Hadoop",
"pyspark"
])
counts = [Link]()

Answer: 4

Explanation:

4 elements in list
Each list item = 1 RDD element

Q130. Package for text analysis:

Answer: NLTK (Natural Language Toolkit)

Common NLP packages:

NLTK ✅
spaCy ✅
TextBlob ✅
Gensim

Quick Reference Summary

Python Basics

Lists: [] mutable
Tuples: () immutable, less memory
Default ports: Flask (5000), Django (8000)

Orange

Dataset: .tab , .csv


Classification: Tree, KNN, RF, SVM, NB
Regression: Linear Regression

PySpark

RDD: Resilient Distributed Dataset


Py4J: Python-Java bridge
Master parameter: Cluster URL

Web Frameworks

Django: Full-stack
Flask: Microframework
WSGI: Gunicorn, uWSGI

NumPy

ndarray: Main object


.npy: Save extension
Row-major order

DevOps

Goals: Speed, Quality, Automation


NOT a goal: Regular hours

You might also like