13 Marks Python
13 Marks Python
ANSWER KEY
PART B
*QB101 (a) (i) Develop a python program to get the details from the user such as student name, age,
address and CGPA and display them.
7 Marks
Ans :
print("\nStudent Details:")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Address: {address}")
print(f"CGPA: {cgpa:.2f}")
(ii) Build a python program to get the principal, rate and time from the user and find the
simple interest for it.
6 Marks
Ans:
1
simple_interest = (principal * rate * time) / 100
QB101 (b) (i) Write a python program to read two integers and perform simple arithmetic
calculation.(+,-,*,/,//,%,**)
7 Marks
Ans:
operations = {
"Addition": a + b,
"Subtraction": a - b,
"Multiplication": a * b,
"Exponentiation": a ** b
return operations
print(f"{operation}: {result}")
(ii) Write a python program to find maximum between three integer numbers using
conditional Expression(Ternary)
6 Marks
Ans:
2
# Function to find the maximum of three numbers using ternary operator
def max_of_three(a, b, c):
return a if (a > b and a > c) else (b if b > c else c)
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print(f"The maximum number is: {max_of_three(a, b, c)}")
QB102 (a) (i) Write a python program to display the sum of all even numbers in the given range.
6 Marks
start = int(input())
end = int(input())
sum=0
for num in range(start, end + 1):
if num % 2 == 0:
sum=sum+num
print("Sum is :",sum)
Ans:
def is_palindrome(number):
num_str = str(number)
reversed_str = num_str[::-1]
if is_palindrome(input_number):
print(f"{input_number} is a palindrome.")
else:
(ii) Write a program to gather individual's details such as name, age, and monthly income,
and determine if the person is eligible for a housing loan. Eligibility criteria: age between 25
to 50 years and monthly income more than 30000. 6
Marks
Ans:
min_age = 25
max_age = 50
min_income = 30000
else:
QB104 (a)
Create a Python program to perform basic geometric calculations using the following user-
defined functions:
calculate_circle_area(radius) to compute the area of a circle.
calculate_rectangle_area(length, width) to compute the area of a rectangle.
calculate_triangle_area(base, height) to compute the area of a triangle.
calculate_square_area(side) to compute the area of a square.
15 Marks
Ans:
import math
4
def calculate_circle_area(radius):
def calculate_square_area(side):
return side ** 2
# Circle
circle_area = calculate_circle_area(radius)
# Rectangle
# Triangle
5
height = float(input("Enter the height of the triangle: "))
# Square
square_area = calculate_square_area(side)
print(f"Area of the square: {square_area:.2f}")
*QB104 (b) (i)To write a Python Program to check if a number is a Perfect number using the concept of
functions.
7 Marks
Ans:
def perfectnumber(n):
factor_sum=0
for i in range(1,n//2+1):
if(n%i==0):
factor_sum+=i
if(n==factor_sum):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")
num=int(input())
perfectnumber(num)
ii) Write a program in Python to find the sum of series (1+(1*2)+(1*2*3)+...till N). 8
Marks
Ans:
n=int(input())
sum_series=0
i=1
while(i<=n):
multiply=1
for j in range(1,i+1):
multiply*=j
sum_series+=multiply
i+=1
print("The sum of the series = ",sum_series)
QB201 (a) What is Set? Explain Python Set in detail with its operations and methods.
Ans
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection which
is unordered, unchangeable*, and unindexed. * Note: Set items are unchangeable, but you
can remove items and add new items.
6
Python Sets – Operations and Examples
A set is a mutable, unordered group of elements, where the elements themselves are
[Link] characteristic of a set is that it may include elements of different types.
This means you can have a group of numbers, strings, and even tuples, all in the same set!
The most common way of creating a set in Python is by using the built-in set() function.
You can also create sets using the curly brace {} syntax:
The set() function takes in an iterable and yields a list of objects which will be inserted into
the set. The {} syntax places the objects themselves into the set.
We already know that sets are mutable. This means you can add/remove elements in a set.
>>> add_set.update(("cello",))
>>> add_Set
{1, 2, 3, 4, 'violin', 'cello'}
7
This is because sets in Python cannot contain duplicates. So, when we tried to add "cello"
again to the set, Python recognized we were trying to add a duplicate element and didn't
update the set. This is one caveat that differentiates sets from lists.
The remove(x) function removes the element x from a set. It returns a KeyError if x is not
part of the set:
>>> sub_set.remove("guitar")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'guitar'
There are a couple of other ways to remove an element(s) from a set:
the discard(x) method removes x from the set, but doesn't raise any error if x is not present in
the set.
the pop() method removes and returns a random element from the set.
the clear() method removes all elements from a set
7
marks
Ans:
QB201 def add_matrices(matrix1, matrix2):
# Example matrices
8
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
print("Resultant Matrix:")
print(row)
ii) Write a python program to create a list of numbers in the range 1 to 10. Then delete all
the even numbers from the list and print the list with odd numbers.
6 marks
Ans:
QB202 (a) Explain classes and objects in Python with an example? Also explain self-keyword
associated the classes.
Class
9
A class in Python is a blueprint for creating objects. It defines attributes (variables) and
methods (functions) that the created objects will have.
Think of a class like a template for a car – it defines the structure, but not the actual car.
Each car built from that blueprint is an object.
Object
An object is an instance of a class. It is a real-world entity with specific values assigned to
its attributes.
Example:
class Employee:
def __init__(self, name, emp_id):
[Link] = name # '[Link]' is instance variable
self.emp_id = emp_id # 'self.emp_id' is also instance variable
def display_info(self):
print(f"Employee Name: {[Link]}")
print(f"Employee ID : {self.emp_id}")
Output:
Employee Name: Alice
Employee ID : EMP001
Employee Name: Bob
Employee ID : EMP002
(b) Write a python code to implement a class Dress with the parameterised constructor ,that
accepts the cloth,cloth-type and quantity , and print the details.
def display_details(self):
print("Dress Details")
print(f"Cloth : {[Link]}")
print(f"Cloth Type : {self.cloth_type}")
print(f"Quantity : {[Link]}")
# Display details
dress.display_details()
OUTPUT:
Enter cloth material: Cotton
Enter cloth type: Shirt
Enter quantity: 5
Dress Details
Cloth : Cotton
Cloth Type : Shirt
Quantity : 5
(a)
i) Write a python program to replace last value of tuples in a list.
Sample input:[(10,20,40),(40,50,60),(70,80,90)]
Sample output:[(10,20,100),(40,50,100),(70,80,100)]
7 Marks
Ans:
"""Replace the last value of each tuple in the list with the specified new value."""
# Sample input
tuples_list = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
new_value = 100
11
ii) Write a python program to return only negative values from the tuples of positive and
negative numbers.
6 Marks
Ans:
def extract_negative_values(tuples_list):
"""Extract and return only the negative values from a list of tuples."""
return negative_values
tuples_list = [(10, -20, 30), (-40, 50, -60), (70, -80, 90), (-10, -30, 40)]
result = extract_negative_values(tuples_list)
(b) Explain the basic List Operations and list slices in details with necessary programs.
Ans:
Basic List Operations
1. Creating a List
You can create a list using square brackets `[]` with comma-separated elements.
# Creating a list
fruits = ['apple', 'banana', 'cherry']
print(fruits)
# Accessing elements
print(fruits[0]) # 'apple'
print(fruits[-1]) # 'cherry'
# Modifying elements
fruits[1] = 'blueberry'
print(fruits) # ['apple', 'blueberry', 'cherry']
3. Adding Elements
12
-append(): Adds an element to the end.
- insert(): Inserts an element at a specified position.
- extend(): Adds elements from another list.
[Link]('date')
[Link](1, 'fig')
[Link](['grape', 'honeydew'])
print(fruits) # ['apple', 'fig', 'blueberry', 'cherry', 'date', 'grape', 'honeydew']
4. Removing Elements
[Link]('fig')
popped = [Link](2)
del fruits[0]
[Link]()
print(fruits) # []
5. List Membership
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
repeated = list1 * 2
print(combined) # [1, 2, 3, 4, 5, 6]
print(repeated) # [1, 2, 3, 1, 2, 3]
List Slicing
Slicing allows you to create a new list by extracting a portion of an existing list using the
syntax `list[start:end:step]`.
Examples
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Reverse a list
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
These operations and slicing techniques are fundamental to working with lists in Python,
enabling you to effectively manage and manipulate collections of data.
(a) Create a Python program to implement stack using List and its built-in methods (append()
and pop() ) in Python. Get five items from the user and save them in stack, then pop three
items from stack and display the stack before and after popped.
Ans
stack=[]
[Link]("One")
[Link]("Two")
[Link]("Three")
QB301
[Link]("Four")
[Link]("Five")
print("Stack - Before Popping")
print(stack)
[Link]()
[Link]()
[Link]()
print("Stack - After Popping")
print(stack)
(b) What is Stack ADT? Explain the operations performed in a stack with examples
Ans
A stack is an ADT in which elements add added and removed from only one end (i.e.,at the
top of the stack). • A stack is a LIFO “last in, first out” structure
• push(n)– This is a user-defined stack method used for inserting an element into the stack. ...
• pop()– We need this method to remove the topmost element from the stack.
isempty()– We need this method to check whether the stack is empty or not.
QB301
Program:
stack = []
# push operations
[Link](10)
[Link](20)
[Link](30)
14
# pop operation
top_element = [Link]()
print("Popped:", top_element) # 30
print("Stack after pop:", stack) # [10, 20]
# peek operation
print("Top element (peek):", stack[-1]) # 20
# check if empty
print("Is stack empty?", len(stack) == 0) # False
# size
print("Stack size:", len(stack)) # 2
(a) Build a Python program to convert given Infix expression to Postfix expression by
following the precedence and associative rule.
The input expression contains only ^ and * . Use dictionary to set the priority for operators.
Use set to hold the operators used in the given expression. Also in the same program
incorporate evaluation for the operands given in an expression
Ans
Operators = set(['+', '-', '*', '/', '(', ')', '^']) # collection of Operators
Priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities of Operators
def infixToPostfix(expression):
while stack:
output+=[Link]()
return output
The priority queue allows efficient management of tasks based on their priorities, ensuring
that higher priority tasks are executed first. This application can be found in operating
systems, real-time systems, and job schedulers. Huffman coding is a popular data
compression algorithm used to compress data efficiently
def __str__(self):
return ' '.join([str(i) for i in [Link]])
if __name__ == '__main__':
myQueue = PriorityQueue()
[Link](12)
[Link](1)
[Link](14)
[Link](7)
print(myQueue)
while not [Link]():
print([Link]())
QB303
QB304 (a) Discuss in detail about the Linked List and its Variations with neat examples.
16
Ans
A linked list is a linear data structure, in which the elements are not stored at contiguous
memory locations. The elements in a linked list are linked using pointers. In simple words,
a linked list consists of nodes where each node contains a data field and a reference(link) to
the next node in the list.
Types Of Linked List:
The node contains a pointer to the next node means that the node stores the address of the
next node in the sequence. A single linked list allows the traversal of data only in one way.
Below is the image for the same:
A doubly linked list or a two-way linked list is a more complex type of linked list that
contains a pointer to the next as well as the previous node in sequence.
Therefore, it contains three parts of data, a pointer to the next node, and a pointer to the
previous node. This would enable us to traverse the list in the backward direction as well.
Below is the image for the same:
A circular linked list is that in which the last node contains the pointer to the first node of
the list.
While traversing a circular linked list, we can begin at any node and traverse the list in any
direction forward and backward until we reach the same node we started. Thus, a circular
linked list has no beginning and no end. Below is the image for the same:
17
(b) Write a Python Program to Insert Strings into a Circular Queue.
class CircularQueue:
def __init__(self, size):
[Link] = size
[Link] = [None] * size # Fixed-size list
[Link] = -1
[Link] = -1
def display(self):
*QB304
if [Link] == -1:
print("Queue is empty.")
return
# Main function
def main():
n = int(input("Enter size of Circular Queue: "))
cq = CircularQueue(n)
Output:
(a) Create a Python function def heaptree(L): to build a tree and find out whether the tree is
max heap and a complete tree, also print the height of the tree. Use appropriate module to
build a binary tree.
Python Code
def is_max_heap_tree(node):
if node is None:
return True
def is_complete_tree_bt(root):
if root is None:
return True
queue = [root]
end = False
while queue:
current = [Link](0)
if [Link]:
if end:
return False
[Link]([Link])
else:
19
end = True
if [Link]:
if end:
return False
[Link]([Link])
else:
end = True
return True
def tree_height_bt(root):
return [Link] if root else 0
def heaptree(L):
print("Building Binary Tree from list:", L)
tree = build(L)
print("\nConstructed Binary Tree:")
print(tree)
is_max = is_max_heap_tree(tree)
is_complete = is_complete_tree_bt(tree)
height = tree_height_bt(tree)
Example Usage:
heaptree([100, 90, 80, 70, 60, 50])
Output:
Building Binary Tree from list: [100, 90, 80, 70, 60, 50]
(b) Write a python code to traverse binary Tree in inorder, preorder and postorder .
In Order Code
QB401
class TreeNode:
def __init__(self, val):
20
[Link] = val
[Link] = None
[Link] = None
def inorderTraversal(root):
answer = []
inorderTraversalUtil(root, answer)
return answer
if root is None:
return
inorderTraversalUtil([Link], answer)
[Link]([Link])
inorderTraversalUtil([Link], answer)
return
root = TreeNode(1)
[Link] = TreeNode(2)
[Link] = TreeNode(3)
[Link] = TreeNode(4)
[Link] = TreeNode(5)
print(inorderTraversal(root))
Preorder Code
class TreeNode:
def __init__(self,val):
[Link] = val
[Link] = None
[Link] = None
def preorderTraversal(root):
answer = []
preorderTraversalUtil(root, answer)
return answer
if root is None:
return
[Link]([Link])
preorderTraversalUtil([Link], answer)
preorderTraversalUtil([Link], answer)
return
21
root = TreeNode(1)
[Link] = TreeNode(2)
[Link] = TreeNode(3)
[Link] = TreeNode(4)
[Link] = TreeNode(5)
print(preorderTraversal(root))
Postorder Code
class TreeNode:
def postorderTraversal(root):
answer = []
postorderTraversalUtil(root, answer)
return answer
if root is None:
return
postorderTraversalUtil([Link], answer)
postorderTraversalUtil([Link], answer)
[Link]([Link])
return
root = TreeNode(1)
[Link] = TreeNode(2)
[Link] = TreeNode(3)
[Link] = TreeNode(4)
[Link] = TreeNode(5)
print(postorderTraversal(root))
(a) Explain in detail about the creation of binary search tree with example.
Ans
QB402
A binary search tree follows some order to arrange the elements. In a Binary search tree, the
value of left node must be smaller than the parent node, and the value of right node must be
greater than the parent node. This rule is applied recursively to the left and right subtrees of
the root.
22
Let's understand the concept of Binary search tree with an example.
In the above figure, we can observe that the root node is 40, and all the nodes of the left
subtree are smaller than the root node, and all the nodes of the right subtree are greater than
the root node.
Similarly, we can see the left child of root node is greater than its left child and smaller than
its right child. So, it also satisfies the property of binary search tree. Therefore, we can say
that the tree in the above image is a binary search tree.
Suppose if we change the value of node 35 to 55 in the above tree, check whether the tree
will be binary search tree or not.
In the above tree, the value of root node is 40, which is greater than its left child 30 but smaller
than right child of 30, i.e., 55. So, the above tree does not satisfy the property of Binary search
tree. Therefore, the above tree is not a binary search tree.
o Searching an element in the Binary search tree is easy as we always have a hint that
which subtree has the desired element.
o As compared to array and linked lists, insertion and deletion operations are faster in
BST.
Now, let's see the creation of binary search tree using an example.
23
Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50
o First, we have to insert 45 into the tree as the root of the tree.
o Then, read the next element; if it is smaller than the root node, insert it as the root of
the left subtree, and move to the next element.
o Otherwise, if the element is larger than the root node, then insert it as the root of the
right subtree.
Now, let's see the process of creating the Binary search tree using the given data element. The
process of creating the BST is shown below -
As 15 is smaller than 45, so insert it as the root node of the left subtree.
As 79 is greater than 45, so insert it as the root node of the right subtree.
90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.
24
Step 5 - Insert 10.
55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree of 79.
12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the right subtree of
10.
25
Step 8 - Insert 20.
20 is smaller than 45 but greater than 15, so it will be inserted as the right subtree of 15.
50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a left subtree of 55.
26
Now, the creation of binary search tree is completed. After that, let's move towards the
operations that can be performed on Binary search tree.
We can perform insert, delete and search operations on the binary search tree.
Searching means to find or locate a specific element or node in a data structure. In Binary
search tree, searching a node is easy because elements in BST are stored in a specific order.
The steps of searching a node in Binary Search tree are listed as follows -
1. First, compare the element to be searched with the root element of the tree.
2. If root is matched with the target element, then return the node's location.
3. If it is not matched, then check whether the item is less than the root element, if it is
smaller than the root element, then move to the left subtree.
4. If it is larger than the root element, then move to the right subtree.
5. Repeat the above procedure recursively until the match is found.
6. If the element is not found or not present in the tree, then return NULL.
Now, let's understand the searching in binary tree using an example. We are taking the binary
search tree formed above. Suppose we have to find node 20 from the below tree.
Step1:
Step2:
27
Step3:
Now, let's see the algorithm to search an element in the Binary search tree.
Now let's understand how the deletion is performed on a binary search tree. We will also see
an example to delete an element from the given tree.
28
In a binary search tree, we must delete a node from the tree by keeping in mind that the
property of BST is not violated. To delete a node from BST, there are three possible situations
occur -
It is the simplest case to delete a node in BST. Here, we have to replace the leaf node with
NULL and simply free the allocated space.
We can see the process to delete a leaf node from BST in the below image. In below image,
suppose we have to delete node 90, as the node to be deleted is a leaf node, so it will be
replaced with NULL, and the allocated space will free.
In this case, we have to replace the target node with its child, and then delete the child node.
It means that after replacing the target node with its child node, the child node will now
contain the value to be deleted. So, we simply have to replace the child node with NULL and
free up the allocated space.
We can see the process of deleting a node with one child from BST in the below image. In
the below image, suppose we have to delete the node 79, as the node to be deleted has only
one child, so it will be replaced with its child 55.
So, the replaced node 79 will now be a leaf node that can be easily deleted.
29
When the node to be deleted has two children
This case of deleting a node in BST is a bit complex among other two cases. In such a case,
the steps to be followed are listed as follows -
The inorder successor is required when the right child of the node is not empty. We can obtain
the inorder successor by finding the minimum element in the right child of the node.
We can see the process of deleting a node with two children from BST in the below image.
In the below image, suppose we have to delete node 45 that is the root node, as the node to
be deleted has two children, so it will be replaced with its inorder successor. Now, node 45
will be at the leaf of the tree so that it can be deleted easily.
A new key in BST is always inserted at the leaf. To insert an element in BST, we have to start
searching from the root node; if the node to be inserted is less than the root node, then search
for an empty location in the left subtree. Else, search for the empty location in the right subtree
and insert the data. Insert in BST is similar to searching, as we always have to maintain the
rule that the left subtree is smaller than the root, and right subtree is larger than the root.
Now, let's see the process of inserting a node into BST using an example.
30
(b) Construct a Python function to build a Binary tree.
3. Print the leaves and leaf count and sum of the leaves of the binary tree.
Ans
class Node:
cnt=0
sum=0
A Red-Black Tree is a type of self-balancing binary search tree (BST). It ensures that the
tree remains approximately balanced during insertions and deletions, maintaining O(log n)
time complexity for search, insertion, and deletion.
32
o Left rotation on 10, recolor → 20 becomes new root.
4. Insert 15
o Goes to the left of 20, then left of 20.
o Recoloring or rotation may happen depending on tree shape and uncle's
color.
5. Insert 25
o Inserted as Red; check for parent/uncle color → rebalance as needed.
6. Insert 5
o Inserted as Red; no violations.
class Node:
def __init__(self, data, color='R'):
[Link] = data
[Link] = color # 'R' for Red, 'B' for Black
[Link] = None
[Link] = None
[Link] = None
class RedBlackTree:
def __init__(self):
[Link] = Node(None, 'B')
[Link] = [Link]
A Splay Tree is a self-adjusting binary search tree. After every access operation (insert,
*QB404
delete, or search), the accessed node is "splayed" to the root using tree rotations. This makes
frequently accessed elements quicker to reach.
33
The most recently accessed node is moved to the root through a process called splaying,
improving access time for future operations involving that node.
Advantages:
• No explicit balancing required.
• Frequently accessed nodes are quicker to reach.
• All standard BST operations (search, insert, delete) are O(log n) amortized time.
10
\
20
•Splay 20 to root (Zig rotation):
CopyEdit
20
/
10
- Splay 30 to root:
- Zig-Zig (20 and 30 are both right children)
- Rotate 20 up, then 30 up:
30
/
20
/
10
34
```python
class Node:
def __init__(self, key):
[Link] = key
[Link] = None
[Link] = None
[Link] = None
class SplayTree:
def __init__(self):
[Link] = None
Ans
Sorting is a way of arranging items in a systematic manner. Quicksort is the widely used
sorting algorithm that makes n log n comparisons in average case for sorting an array of n
elements. It is a faster and highly efficient sorting algorithm. This algorithm follows the divide
and conquer approach. Divide and conquer is a technique of breaking down the algorithms
into subproblems, then solving the subproblems, and combining the results back together to
solve the original problem.
Divide: In Divide, first pick a pivot element. After that, partition or rearrange the array into
two sub-arrays such that each element in the left sub-array is less than or equal to the pivot
element and each element in the right sub-array is larger than the pivot element.
Quicksort picks an element as pivot, and then it partitions the given array around the picked
pivot element. In quick sort, a large array is divided into two arrays in which one holds values
QB501
that are smaller than the specified value (Pivot), and another array holds the values that are
greater than the pivot.
After that, left and right sub-arrays are also partitioned using the same approach. It will
continue until the single element remains in the sub-array.
Picking a good pivot is necessary for the fast implementation of quicksort. However, it is
typical to determine a good pivot. Some of the ways of choosing a pivot are as follows -
o Pivot can be random, i.e. select the random pivot from the given array.
o Pivot can either be the rightmost element of the leftmost element of the given array.
36
o Select median as the pivot element.
Algorithm
Algorithm:
Partition Algorithm:
To understand the working of quick sort, let's take an unsorted array. It will make the concept
more clear and understandable.
37
In the given array, we consider the leftmost element as pivot. So, in this case, a[left] = 24,
a[right] = 27 and a[pivot] = 24.
Since, pivot is at left, so algorithm starts from right and move towards left.
Now, a[pivot] < a[right], so algorithm moves forward one position towards left, i.e. -
Because, a[pivot] > a[right], so, algorithm will swap a[pivot] with a[right], and pivot moves
to right, as -
Now, a[left] = 19, a[right] = 24, and a[pivot] = 24. Since, pivot is at right, so algorithm starts
from left and moves to right.
38
Now, a[left] = 9, a[right] = 24, and a[pivot] = 24. As a[pivot] > a[left], so algorithm moves
one position to right as -
Now, a[left] = 29, a[right] = 24, and a[pivot] = 24. As a[pivot] < a[left], so, swap a[pivot] and
a[left], now pivot is at left, i.e. -
Since, pivot is at left, so algorithm starts from right, and move to left. Now, a[left] = 24,
a[right] = 29, and a[pivot] = 24. As a[pivot] < a[right], so algorithm moves one position to
left, as -
Now, a[pivot] = 24, a[left] = 24, and a[right] = 14. As a[pivot] > a[right], so, swap a[pivot]
and a[right], now pivot is at right, i.e. -
Now, a[pivot] = 24, a[left] = 14, and a[right] = 24. Pivot is at right, so the algorithm starts
from left and move to right.
39
Now, a[pivot] = 24, a[left] = 24, and a[right] = 24. So, pivot, left and right are pointing the
same element. It represents the termination of procedure.
Element 24, which is the pivot element is placed at its exact position.
Elements that are right side of element 24 are greater than it, and the elements that are left
side of element 24 are smaller than it.
Now, in a similar manner, quick sort algorithm is separately applied to the left and right sub-
arrays. After sorting gets done, the array will be -
Linear Search (or Sequential Search) is the simplest searching algorithm. It works by
scanning each element of a list one by one until the desired value is found or the list ends.
Characteristics:
• Works on unsorted or sorted data.
• Simple to implement.
• Time complexity:
o Best Case: O(1) → Element is at the beginning.
o Worst Case: O(n) → Element is at the end or not present.
*QB501
o Average Case: O(n)
Working:
1. Start from the first element.
2. Compare each element with the target.
3. If match is found, return the index.
4. If the end of the list is reached without finding it, return a failure message (e.g., -1 or
"Not Found").
Example:
Let's search for the number 25 in the list:
40
arr = [10, 15, 20, 25, 30]
target = 25
Step-by-step:
• Compare 10 with 25 → No match
• Compare 15 with 25 → No match
• Compare 20 with 25 → No match
• Compare 25 with 25 → Match found at index 3
# Example usage:
arr = [10, 15, 20, 25, 30]
target = 25
result = linear_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Output:
Element found at index 3
Advantages:
1) Simplicity
• Very easy to implement and understand.
• Requires minimal programming logic.
2)No Sorting Required
• Works efficiently on unsorted data, unlike algorithms like binary search that require
sorting first.
3)Versatile
• Works on arrays, linked lists, strings, and other iterable data structures.
(a)
Describe in detail about Binary Search with an example.
Ans
What is Search?
Search is a utility that enables its user to find documents, files, media, or any other type of
QB502 data held inside a database. Search works on the simple principle of matching the criteria
with the records and displaying it to the user. In this way, the most basic search function
works.
41
until the required value is located and displayed to the user in the search result. Binary
search is commonly known as a half-interval search or a logarithmic search.
• The search process initiates by locating the middle element of the sorted array of
data
• After that, the key value is compared with the element
• If the key value is smaller than the middle element, then searches analyses the upper
values to the middle element for comparison and matching
• In case the key value is greater than the middle element then searches analyses the
lower values to the middle element for comparison and matching
42
F. These iterations continue until the array is reduced to only one element, or the item
to be found becomes the middle of the array.
Example 2
Let’s look at the following example to understand the binary search working
A. You have an array of sorted values ranging from 2 to 20 and need to locate 18.
B. The average of the lower and upper limits is (l + r) / 2 = 4. The value being searched
is greater than the mid which is 4.
C. The array values less than the mid are dropped from search and values greater than
the mid-value 4 are searched.
D. This is a recurrent dividing process until the actual item to be s.
(b) write a Python program for Dijkstra's single source shortest path algorithm.
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
[Link] = [[0 for column in range(vertices)] for row in range(vertices)]
[Link](dist)
# Driver code
g = Graph(9)
[Link] = [
[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
[Link](0)
OUTPUT:
(a) What is Graph? Explain the terms and types and applications of Graph with examples.
What is a Graph?
QB504 A graph is a non-linear data structure made up of nodes (also called vertices) and edges
(also called arcs) that connect these nodes. Graphs are widely used to represent networks,
such as social networks, computer networks, or transportation systems.
Applications of Graphs:
13. Social Networks: Graphs are used to model social connections, where vertices
represent people, and edges represent friendships.
14. Web Page Linkage: The structure of the World Wide Web can be represented as a
graph, where pages are vertices, and hyperlinks between them are edges.
15. Transportation Networks: Cities or locations can be modeled as vertices, and roads
or transportation routes between them as edges.
16. Computer Networks: Devices in a network are represented as vertices, and
communication links between them are represented as edges.
17. Recommendation Systems: Graphs are used in recommendation systems, where
items are vertices, and edges represent relationships (e.g., user likes item or user
bought item).
18. Dependency Resolution: In project management or compilation, tasks and their
dependencies can be represented as a directed acyclic graph (DAG).
import heapq
import sys # Library for INT_MAX
class Graph:
def __init__(self, vertices):
self.V = vertices
[Link] = [[0 for column in range(vertices)]
45
for row in range(vertices)]
for v in range(self.V):
if key[v] < min_val and mstSet[v] is False:
min_val = key[v]
min_index = v
return min_index
# Function to construct and print MST for a graph
def primMST(self):
key = [[Link]] * self.V
parent = [None] * self.V # Array to store constructed MST
key[0] = 0 # Make key 0 so that this vertex is picked first
mstSet = [False] * self.V
parent[0] = -1 # First node is always the root
for _ in range(self.V):
u = [Link](key, mstSet)
mstSet[u] = True
for v in range(self.V):
if [Link][u][v] > 0 and mstSet[v] is False and key[v] >
[Link][u][v]:
key[v] = [Link][u][v]
parent[v] = u
[Link](parent)
# Example usage:
g = Graph(5)
[Link] = [
[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]
]
[Link]()
Output:
46
47