Python-2 Mid Sem Solutions
Python-2 Mid Sem Solutions
i. "If it looks like a duck and quacks like a duck, it probably is a duck." What
does this mean in Python's Duck Typing? How does it support
Polymorphism? Give an example.
ii. What happens if a user tries to access a private attribute (__attribute)
directly? How can you retrieve the value of a private attribute without
modifying the class definition?
Ans (i):
Duck Typing is a concept in dynamic programming languages like Python where the
type or class of an object is less important than the methods or behaviors it
supports.
Instead of forcing objects to inherit from a common base class (like in statically-typed
languages), Python allows objects to be used interchangeably as long as they implement
the expected methods.
Example:
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
def animal_sound(animal):
print(animal.speak())
dog = Dog()
cat = Cat()
Ans (ii):
If a user tries to access a private attribute directly using object.__attribute, Python will
raise an AttributeError because private attributes are name-mangled to prevent direct
access.
class Person:
def __init__(self):
self.__name = "XYZ"
p = Person()
print(p._Person__name) # Output: XYZ
(b) A bank wants to restrict direct access to an account’s balance. Write a Python (2)
class, BankAccount, that uses getter and setter methods to manage the balance
securely. Ensure that the balance cannot be accessed or modified directly. The
class should have:
Ans:
class BankAccount:
def __init__(self, initial_balance):
self.__balance = 0 # private attribute
self.set_balance(initial_balance) # use setter to initialize
# Getter method
def get_balance(self):
return self.__balance
# Setter method with validation
def set_balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Balance cannot be negative.")
# Deposit method
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited: {amount}")
else:
print("Deposit amount must be positive.")
# Withdraw method
def withdraw(self, amount):
if amount <= 0:
print("Withdrawal amount must be positive.")
elif amount > self.__balance:
print("Insufficient funds.")
else:
self.__balance -= amount
print(f"Withdrew: {amount}")
account = BankAccount(1000)
# Access via getter
print("Balance:", account.get_balance()) # Output: 1000
# Deposit money
account.deposit(500) # Deposited: 500
print("Balance:", account.get_balance()) # Output: 1500
# Withdraw money
account.withdraw(300) # Withdrew: 300
print("Balance:", account.get_balance()) # Output: 1200
x = Data(10)
y=x
y.value = 20
print(x.value)
What is the output of the above program? Why does modifying y.value also affect
x.value?
Ans:
The value is 20.
y = x does not create a copy of the object — it just creates a new reference (y)
pointing to the same object as x. That’s why y.value = 20 modifies the shared
object's value attribute to 20.
2 (a) What is recursion? Implement a recursive solution to compute the nth Fibonacci (2)
number and analyze its time complexity.
Ans:
(b) You are given a sorted list [2, 5, 8, 12, 16, 23, 38, 56]. Implement a recursive binary (2)
search function to locate the index of the element 23. If the element is not found,
return -1. Furthermore, evaluate the time complexity and space complexity of your
recursive binary search solution.
Ans:
def binary_search_recursive(arr, target, low, high):
if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
return binary_search_recursive(arr, target, low, mid - 1)
else:
return binary_search_recursive(arr, target, mid + 1, high)
(c) Given a list of integers, implement a Python program to sort the list using the (2)
insertion sort algorithm. For example, if the list is [12, 11, 13, 5, 6], write the code
to sort it and display the sorted result. Furthermore, analyze the best-case and
worst-case time complexities of the insertion sort algorithm.
Ans:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
arr[j + 1] = key
Time complexity:
Best Case: 𝑂(𝑛)
Worst Case: 𝑂(𝑛 )
3 (a) Consider the following Python code: (2)
What is the expected output of this code? Explain the significance of the output in
the context of Parts-of-Speech tagging.
Ans:
[('Python', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('wonderful', 'JJ'), ('programming', 'NN'),
('language', 'NN')]
This output represents the Part-of-Speech (POS) tagging of each word in the sentence.
The TextBlob library uses natural language processing to assign grammatical tags like
NNP (proper noun), VBZ (verb, 3rd person singular), DT (determiner), JJ (adjective),
and NN (noun). POS tagging is fundamental in text analysis, allowing programs to
understand sentence structure and meaning—supporting tasks like syntactic parsing,
named entity recognition, and information retrieval.
(b) Write a Python program using TextBlob to classify the sentiment (positive, (2)
negative, or neutral) of a list of sentences. The program should:
Ans:
from textblob import TextBlob
Output:
Sentence: "I love the weather today!" → Sentiment: Positive
Sentence: "The food was awful, and the service was terrible." → Sentiment: Negative
Sentence: "It was an average experience." → Sentiment: Negative
(c) Write a Python program that performs the following tasks using TextBlob: (2)
"Running quickly towards the finishing line, the exhausted runners were
hoping to win. There were different varieties of prizes."
Perform stemming and lemmatization to return the base forms of each word.
Ans:
from textblob import TextBlob
# Input sentence
sentence = "Running quickly towards the finishing line, the exhausted runners were
hoping to win. There were different varieties of prizes."
# Display results
print("Original Words: ", list(tokens))
print("Stemmed Words: ", stemmed_words)
print("Lemmatized Words: ", lemmatized_words)
Lemmatization produces more readable and grammatically correct words, like “prize”
from “prizes”, while simple stemming results in forms like “varieti” from “varieties”,
which are not valid English words. According to the textbook, lemmatization is
preferred for applications where human readability and correct grammar matter, as it
reduces words to their dictionary base forms.
4 (a) What is Cognitive Computing? Explain how IBM Watson Cloud leverages (2)
cognitive computing to enhance its capabilities.
Ans: Cognitive Computing refers to systems that simulate human thought processes in
a computerized model. It involves self-learning systems that use data mining, pattern
recognition, and natural language processing to mimic the way the human brain works.
(b) Write a Python program to fetch user details, including the follower count, from (2)
Twitter's API using the tweepy package and authentication credentials.
Ans:
import tweepy
(c) Write a Python code snippet to implement the K-NN (K-Nearest Neighbors) (2)
algorithm and split the data into training and testing sets, with 70% for training
and 30% for testing. Ensure reproducibility by setting the random_state
parameter to 42.
Ans:
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
5 (a) What is the difference between supervised and unsupervised machine learning? (2)
Provide examples of algorithms used in each type, and explain when each
approach is typically used.
Ans:
Supervised Learning
The computer learns from labeled data (input-output pairs). You tell it the correct
answers during training.
Unsupervised Learning
The computer learns from unlabeled data (no correct answers given). It finds hidden
patterns on its own.
Ans:
Simple Linear Regression – It is the simplest of the regression algorithms. It comes
under ‘regression’ (Supervised Learning) and deals with data having 1 dependent
variable and 1 independent variable.
Mathematical equation: 𝑦 = 𝑚𝑥 + 𝑐
where, ydependent variable, xindependent variable, mslope¸ cy-intercept.
If both training and test errors are high in a regression model, the most likely cause
is underfitting. Underfitting happens when the model is too simple to capture the
underlying patterns in the data.
Possible causes of Underfitting:
The model is not complex enough.
Important features are missing.
Insufficient training.
Poor data preprocessing.
(c) Consider the following confusion matrix for a binary classification problem. (2)
Compute the Accuracy, Precision, Recall, and F1-score:
Where TP, FN, FP, and TN represent True Positives, False Negatives, False Positives,
and True Negatives, respectively.
Ans:
We have the following:
Accuracy = = 0.85.
F1-score = = 0.84.