0% found this document useful (0 votes)
4 views9 pages

Python-2 Mid Sem Solutions

The document provides explanations and implementations of various Python programming concepts, including Duck Typing, recursion, binary search, sentiment analysis, and cognitive computing. It covers class definitions for managing bank accounts, sorting algorithms, and machine learning techniques like K-NN and linear regression, along with their complexities. Additionally, it discusses performance metrics for classification models using confusion matrices.
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)
4 views9 pages

Python-2 Mid Sem Solutions

The document provides explanations and implementations of various Python programming concepts, including Duck Typing, recursion, binary search, sentiment analysis, and cognitive computing. It covers class definitions for managing bank accounts, sorting algorithms, and machine learning techniques like K-NN and linear regression, along with their complexities. Additionally, it discusses performance metrics for classification models using confusion matrices.
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
You are on page 1/ 9

1 (a) Answer the following questions: (2)

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.

Polymorphism allows objects of different types to be used interchangeably if they


implement the same behaviour. Duck typing enables this by focusing on behaviour
rather than inheritance.

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()

animal_sound(dog) # Output: Woof!


animal_sound(cat) # Output: Meow!

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:

 A constructor to initialize the balance.


 A getter and setter for the balance.
 Methods to deposit and withdraw money, with checks for valid amounts.

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

(c) class Data: (2)


def __init__(self, value):
self.value = value

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.

Reason: Both x and y refer to the same object in memory.

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:

Recursion is a programming technique where a function calls itself to solve a smaller


instance of the same problem. A recursive function must have:

1. Base Case(s) – to stop the recursion.


2. Recursive Case(s) – where the function calls itself with a smaller input.

Recursive Fibonacci Implementation:

The Fibonacci sequence is defined as:

F(0)=0,F(1)=1,F(n)=F(n−1)+F(n−2) for n>1

Here is a simple recursive implementation:


def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)

Example: Compute the 6th Fibonacci number


print(fibonacci(6)) # Output: 8

(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)

arr = [2, 5, 8, 12, 16, 23, 38, 56]


target = 23
result = binary_search_recursive(arr, target, 0, len(arr) - 1)

print("Index of", target, ":", result)


Output: Index of 23 : 5

 Time Complexity: O(log n)


 Space Complexity: O(log n)

(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

while j >= 0 and arr[j] > key:


arr[j + 1] = arr[j]
j-=1

arr[j + 1] = key

arr = [12, 11, 13, 5, 6]


insertion_sort(arr)
print("Sorted list:", arr)

Time complexity:
Best Case: 𝑂(𝑛)
Worst Case: 𝑂(𝑛 )
3 (a) Consider the following Python code: (2)

from textblob import TextBlob


text = "Python is a wonderful programming language."
blob = TextBlob(text)
print(blob.tags)

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:

Accept sentences as input. Perform sentiment analysis using TextBlob. Classify


each sentence as positive, negative, or neutral based on the polarity score.

Test the program using the following sentences:

"I love the weather today!"

"The food was awful, and the service was terrible."

"It was an average experience."

Ans:
from textblob import TextBlob

# List of test sentences


sentences = [
"I love the weather today!",
"The food was awful, and the service was terrible.",
"It was an average experience."
]

# Function to classify sentiment using TextBlob


def classify_sentiment(text):
blob = TextBlob(text)
polarity = blob.sentiment.polarity
if polarity > 0:
return "Positive"
elif polarity < 0:
return "Negative"
else:
return "Neutral"

# Analyze each sentence


for sentence in sentences:
result = classify_sentiment(sentence)
print(f"Sentence: \"{sentence}\" → Sentiment: {result}")

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)

 Take the following sentence:

"Running quickly towards the finishing line, the exhausted runners were
hoping to win. There were different varieties of prizes."

 Tokenize the sentence into words.

 Perform stemming and lemmatization to return the base forms of each word.

Discuss which output (stemming or lemmatization) is more readable and explain


why.

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."

# Create a TextBlob object


blob = TextBlob(sentence)

# Tokenize the sentence into words


tokens = blob.words

# Simple stemming using TextBlob's Word.stem


stemmed_words = [word.stem() for word in tokens]

# Lemmatization using TextBlob's Word.lemmatize


lemmatized_words = [word.lemmatize() for word in tokens]

# 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.

IBM Watson Cloud leverages cognitive computing by using machine learning


algorithms and natural language processing to analyze large volumes of unstructured
data, understand context, and provide intelligent, evidence-based responses, thereby
enhancing decision-making and automation.

(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

# Replace with your own credentials


consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'

# Authenticate and create API object


auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret,
access_token, access_token_secret)
api = tweepy.API(auth)

# Fetch user details


user = api.get_user(screen_name='twitter_username')
print(f'Name: {user.name}')
print(f'Followers: {user.followers_count}')

(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

# Load sample dataset


iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3, random_state=42)

# Create and train the K-NN model


knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)

# Evaluate the model


accuracy = knn.score(X_test, y_test)
print(f"Accuracy: {accuracy:.2f}")

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.

The simplest algorithm of classification type (predicting categories/ discrete labels)


in Supervised Learning is k-nearest neighbors (KNN).

The simplest algorithm of regression type (predicting numbers continuous values) in


Supervised Learning is Simple linear Regression.

Unsupervised Learning

The computer learns from unlabeled data (no correct answers given). It finds hidden
patterns on its own.

The simplest algorithm of Clustering (grouping similar things) in Unsupervised


Learning is k-means clustering.

The simplest algorithm of Dimensionality Reduction (simplifying data) in


Unsupervised Learning is Dimensionality Reduction using PCA.
(b) Define simple linear regression and provide its mathematical equation. (2)
Furthermore, if both training and test errors are high in a regression model, what
is the likely cause, and how can it be addressed?

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, ydependent variable, xindependent variable, mslope¸ cy-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.

How to Address Underfitting:


Increase model complexity.
Include more relevant features.
Transform existing features to better capture relationships.
Train longer or tune hyperparameters.
Check data quality.

(c) Consider the following confusion matrix for a binary classification problem. (2)
Compute the Accuracy, Precision, Recall, and F1-score:

Actual\Predicte Positive (1) Negative (0)


d
Positive (1) TP (40) FN (10)

Negative (0) FP (5) TN (45)

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.

Precision (p) = = 0.88.

Recall (r) = = 0.8.

F1-score = = 0.84.

You might also like