Professional Documents
Culture Documents
Python 2022-23
Python 2022-23
B.Tech.
(SEM IV) THEORY EXAMINATION 2022-23
PYTHON PROGRAMMING
MODEL SOLUTION
Note: Attempt all Sections. If require any missing data; then choose suitably.
SECTION A
# Example usage
my_list = [4, 2, 7, 1, 9, 5]
search_value = 7
SECTION B
c. Compare list and tuple data structure with suitable examples. Explain the
conceptof list comprehension.
Characteristic Lists Tuples
Mutable (can be modified after Immutable (cannot be
Mutability
creation) modified after creation)
Syntax Created using parentheses
Created using square brackets [ ] ( )
Dynamic Sizing Yes No
Elements can be added, modified, Elements cannot be
Modifications
removed changed after creation
Suitable for constant
Usage Suitable for dynamic collections
collections
Example fruits = ['apple', 'banana'] coordinates = (3, 4)
Example fruits.append('orange') Not applicable
Modification
Classes are the Python representation for “Abstract Data Types”. Considering Stack
as ADT. We need to understand what operations it needs to perform:
Push(): To insert the element in stack list
Pop(): To delete the element from stack list
Create(): To create a stack
Isempty: To check whether stack empty or not
Size(): to Know size of stack
such signature of various operation on ADT under consideration are said to be
interface to ADT.
The provided class Stack represents a basic implementation of a stack data structure
using Python. A stack is a linear data structure that follows the Last-In-First-Out
(LIFO) principle, where the last element added is the first one to be removed. The
class includes methods to interact with the stack:
IsEmpty(self): This method checks if the stack is empty by comparing the list
items with an empty list. If the two lists are equal, it returns True; otherwise, it
returns False.
push(self, item): This method adds an item to the top of the stack by appending it
to the items list.
pop(self): This method removes and returns the top item from the stack using the
pop() method of the items list.
top(self): This method returns the top item of the stack (the last item in the items
list) without removing it. It uses indexing to access the last element.
size(self): This method returns the number of items in the stack using the built-in
len() function.
e. Describe python program to implement selection sort. Simulate your code
on thefollowing data
2,52,1,5,2,54,62,64.
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
# Example data
data = [2, 52, 1, 5, 2, 54, 62, 64]
After sorting, the data becomes: [1, 2, 2, 5, 52, 54, 62, 64]. The selection sort algorithm
performs n - 1 comparisons in the first iteration, n - 2 in the second, and so on. It's not
the most efficient sorting algorithm for large datasets, but it's easy to understand and
implement.
SECTION C
3. Attempt any one part of the following: 10x1=10
a. Discuss various categories of operators in python. Find and explain
stepwisesolution of following expressions if a=3, b=5, c=10.
i) a &b<<2//5**2+c^b
ii) b>>a**2<<2 >> b**2^c**3
In Python, operators are special symbols or keywords that perform
operations on one or more operands. Operators are categorized into several
groups based on their functionality and purpose:
1. Arithmetic Operators: These operators perform arithmetic operations like
addition, subtraction, multiplication, division, etc.
2. Comparison Operators: Also known as relational operators, they are used to
compare values and return boolean results (True or False).
3. Logical Operators: These operators perform logical operations like AND,
OR, NOT on boolean values.
4. Bitwise Operators: They perform bit-level operations on integers.
5. Assignment Operators: These operators assign values to variables and can
perform an operation in conjunction with assignment.
6. Identity Operators: They are used to compare the memory locations of two
objects.
7. Membership Operators: These operators test if a value is a member of a
sequence, like a list, string, or tuple.
8. Unary Operators: These operators work on a single operand.
Now, let's break down and explain the stepwise solutions of the given
expressions for the provided values a=3, b=5, and c=10.
i) a &b<<2//5**2+c^b # first evaluate **
a &b<<2//25+c^b # evaluate //
a &b<<0+c^b #evaluate + operation 0+10 =10
a & 5120 ^b # evaluate <<
3 & 5120 ^5 # evaluate &
0^5 # evaluate ^
5 Ans.
ii) b>>a**2<<2 >> b**2^c**3 # first evaluate ** in right to left
b>>9<<2 >> 25^1000 # now evaluate << or >> in left to right order
5>>9<<2 >> 25^1000 # evaluate left most right shift
0<<2>>25^1000 # evaluate next shif operation
0>>25^1000 # evaluate next shift
0^1000 # finally evaluate xor to get ans.
1000 Ans.
Python 2 Python 3
>>7 / 5 >>7/5
Results: 1 Results: 1.4
print “message” print (“Message”)
Xrange Range
Features:
b. Write a program that accepts sequence of lines as input and prints the
linesafter making all characters in the sentence capitalized.
e.g. If Input:
Hello world
Practice makes perfect
Then, Output:
HELLO WORLD
PRACTICE MAKES PERFECT
a. Discuss list data structure of python. Explain various inbuilt methods of list
withsuitable example of each.
A list is a versatile and fundamental data structure in Python that allows you to
store a collection of items. Lists are ordered, mutable (modifiable), and can
contain elements of different data types, including other lists. Lists are defined
using square brackets [] and elements are separated by commas.
Example of creating a list:
fruits = ['apple', 'banana', 'orange', 'grape']
Various Inbuilt Methods of List with Examples:
append(item): Adds an element to the end of the list. E.g.
fruits = ['apple', 'banana', 'orange']
fruits.append('grape')
# fruits is now ['apple', 'banana', 'orange', 'grape']
index(item): Returns the index of the first occurrence of the specified item.
fruits = ['apple', 'banana', 'orange']
index = fruits.index('banana')
# index is 1
count(item): Returns the number of times the specified item appears in the
list.
fruits = ['apple', 'banana', 'banana', 'orange']
count = fruits.count('banana')
# count is 2
get(key, default=None): Returns the value associated with the key. If the key is
not found, returns the default value.
student = {'name': 'Alice', 'age': 20}
age = student.get('age', 0)
grade = student.get('grade', 'N/A')
a. Discuss the concept of Iterators in python. Explain, how we can create text
file in python? Describe python program to write the number of letters and
digits in given input string into a File object.
Iterators are used with objects that implement two methods: __iter__() and
__next__(). The __iter__() method returns the iterator object itself, and the
__next__() method returns the next value from the iterator.
You can create a text file in Python using the built-in open() function and
specifying the file mode as 'w' (write). This mode will create a new file or
overwrite an existing file with the same name.
python
file = open('example.txt', 'w')
file.write("Hello, this is a text file.")
file.close()
Python program that takes an input string and writes the count of letters and digits
into a text file:
def count_letters_digits(input_str):
letters = 0
digits = 0
for char in input_str:
if char.isalpha():
letters += 1
elif char.isdigit():
digits += 1
return letters, digits
input_str = input("Enter a string: ")
letters_count, digits_count = count_letters_digits(input_str)
with open('count.txt', 'w') as file:
file.write(f"Number of letters: {letters_count}\n")
file.write(f"Number of digits: {digits_count}\n")
print("Counts written to file 'count.txt'")
1. Single Inheritance: In single inheritance, a class inherits from only one base class.
python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
dog = Dog()
print(dog.speak()) # Output: Woof!
1. Static Method: A static method belongs to a class rather than an instance. It can be
called using the class name and doesn't have access to instance-specific or class-
specific attributes.
python
class MathOperations:
@staticmethod
def add(x, y):
return x + y
result = MathOperations.add(3, 5)
print(result) # Output: 8
3. Class Method: A class method operates on the class itself and can access class
attributes and methods.
python
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
@classmethod
def get_pi(cls):
return cls.pi
circle = Circle(3)
print(circle.get_pi()) # Output: 3.14159
7. Attempt any one part of the following: 10x1=10
a. Explain the Tower of Hanoi problem and its recursive solution in Python.
The Tower of Hanoi is a classic mathematical puzzle that involves moving a stack of discs
from one peg to another, with the help of an auxiliary peg, following certain rules:
The problem starts with all the discs on one peg (source peg) arranged in decreasing order
of size, and the goal is to move all the discs to another peg (destination peg) while using a
third peg (auxiliary peg) as temporary storage.
The Tower of Hanoi problem can be elegantly solved using a recursive algorithm. The key
insight is to break down the problem into smaller subproblems by moving a smaller subset
of discs. The steps can be summarized as follows:
1. Move n-1 discs from the source peg to the auxiliary peg, using the destination peg
as the auxiliary storage.
2. Move the remaining largest disc from the source peg to the destination peg.
3. Move the n-1 discs from the auxiliary peg to the destination peg, using the source
peg as the auxiliary storage.
# Example usage
n=3
tower_of_hanoi(n, 'A', 'C', 'B')
b. Write python program to implement merge sort algorithm. Discuss, how we
can compare the time complexity of two algorithms?
Merge Sort is a divide-and-conquer sorting algorithm that divides the unsorted list
into smaller sublists, sorts them, and then merges the sorted sublists to produce
the final sorted list.
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
merge_sort(arr)
print("Sorted array:", arr)
timeit.timeit() function can be used to measure the execution time of the provided code snippets
(lambda functions) for each input size. The number=1 argument specifies that each code snippet
is executed only once that can be changed also. By comparing the execution times, you can
observe the relative performance of the Merge Sort and Bubble Sort algorithms as the input size
increases. E.g.
input_sizes = [100, 1000, 5000, 10000]
for size in input_sizes:
random_array = [random.randint(1, 1000) for _ in range(size)]
merge_sort_time = timeit.timeit(lambda:merge_sort(random_array.copy()),
number=1)
bubble_sort_time = timeit.timeit(lambda:bubble_sort(random_array.copy()),
number=1)
print(f"Input size: {size}")
print(f"Merge Sort Time: {merge_sort_time:.6f} seconds")
print(f"Bubble Sort Time: {bubble_sort_time:.6f} seconds")