Python Programming and Data Structures
Python Programming and Data Structures
Example:
lambda x: x + 5 Example:
Output:
3) peek() – View top element without removing
Postfix = A B * C D * + b) Write the elements in BFS and DFS of the
Name: Rahul
Marks: 85 top = stack[-1]
a) What is Queue? Explain types of Queue. [4] following Binary Tree.
print(top)
Queue (Definition)
) Explain function in Python with suitable example. [4]
A function in Python is a block of reusable code that performs a specific task.
4) isEmpty() – Check if stack is empty A Queue is a linear data structure that follows the FIFO (First In First Out) principle. 1) BFS (Breadth First Search) – Level Order Traversal
The element inserted first is removed first.
Functions help in reducing code repetition, improving readability, and organizing programs. if len(stack) == 0: Visit nodes level by level:
print("Stack is empty") Types of Queue:
Syntax of a function Level 1: a
Stacks are used in function calls, expression conversion, undo operations, etc. Level 2: b, c
def function_name(parameters):
statements Level 3: d, e, f, g
return value 1) Simple / Linear Queue Level 4: h, i, j
Example: c) Write Prefix and Postfix Expression of: • Elements inserted at rear, deleted from front. BFS Traversal:
• Example operations: enqueue, dequeue.
def add(a, b): A*B+C*D abcdefghij
result = a + b
return result
Given expression is:
# calling function 2) Circular Queue
print(add(5, 10)) 𝐴×𝐵+𝐶×𝐷 2) DFS (Depth First Search)
• Last position connects back to first.
Output: • Solves space wastage problem of linear queue.
DFS can be Preorder / Inorder / Postorder, but if the question says DFS, we normally give preorder.
This is of type:
15
(𝐴 ∗ 𝐵) + (𝐶 ∗ 𝐷)
DFS (Preorder: Root → Left → Right)
In this example, add() is a function that takes two numbers and returns their sum. 3) Priority Queue
Visit in this order:
• Each element has a priority.
• Element with highest priority is removed first (not based on order of arrival). a
1) Prefix (Polish Notation) b
b) What is stack? Explain any four stack operations in data d
structure using Python. [4] Operator comes before operands e
4) Double Ended Queue (Deque) h
Stack (Definition) i
• Insertion and deletion possible from both ends. c
2) values()
Types of Linked List
b) Explain various operators in Python 6) Membership Operators Returns all values in the dictionary.
List. [6]
and, or, not Both ends connected.
Pass 1
A ↔ B ↔ C ↔ A
19 moves to end of first pass:
Linked List (Definition)
4) Assignment Operators a) Explain any four methods in Dictionary. [4]
29 39 79 59 49 69 19 89
A Linked List is a linear data structure in which elements are stored in nodes, and each node contains:
29 39 59 49 69 19 79 89
Used to assign values.
29 39 49 59 19 69 79 89 a) Write a program to reverse a given string using stack. [4] Example: 3) Circular Linked List
29 39 49 19 59 69 79 89
29 39 19 49 59 69 79 89 square = list(map(lambda x: x*x, nums)) • The last node points back to the first node.
29 19 39 49 59 69 79 89 Program:
• No node contains None.
19 29 39 49 59 69 79 89 (after full sorting) Output: [1, 4, 9, 16, 25]
def reverse_string(s):
stack = [] A → B → C → A
Bubble sort continues passes, but the list is already sorted.
# push characters into stack
for char in s: 3) reduce()
[Link](char)
4) Circular Doubly Linked List
Final Sorted List: rev = "" Used to reduce a sequence to a single value (requires functools module). • Combines both doubly + circular structures.
# pop characters from stack
while stack: Syntax: A ↔ B ↔ C (and C ↔ A)
19 29 39 49 59 69 79 89 rev += [Link]()
reduce(function, sequence)
return rev Q4(a) Traverse the following tree using preorder, inorder and
# test Example: postorder traversal techniques.
c) Write a program to create singly linked list. [4] string = "HELLO"
print("Original:", string) from functools import reduce Edges:
print("Reversed:", reverse_string(string)) total = reduce(lambda x, y: x + y, nums)
Python Program for Singly Linked List
• a → b, a → c
Output: Output: 15 • b→d
class Node:
def __init__(self, data):
Original: HELLO • c → e, c → f
[Link] = data
Reversed: OLLEO • e→g
[Link] = None
• f → h, f → i
class LinkedList: c) Explain the types of linked list. [4]
def __init__(self): So the tree structure is:
[Link] = None b) Describe the use of filter(), map() and reduce() functions in A linked list is a dynamic data structure made of nodes, and each node has:
# insert at end Python. [4] /
a
\
def insert(self, data): • data b c
new_node = Node(data) 1) filter() • pointer to the next node / / \
d e f
if [Link] is None: / / \
[Link] = new_node Used to filter elements from a sequence based on a condition. Types of Linked Lists: g h i
return
Syntax:
temp = [Link] Preorder (Root → Left → Right)
while [Link]: filter(function, sequence)
temp = [Link] 1) Singly Linked List Visit:
[Link] = new_node
Example: • Each node points to the next node.
# display list • a, b, d, c, e, g, f, h, i
• Traversal in one direction only.
def display(self): nums = [1, 2, 3, 4, 5]
temp = [Link] even = list(filter(lambda x: x % 2 == 0, nums)) Preorder: a b d c e g f h i
while temp: A → B → C → None
print([Link], end=" -> ")
temp = [Link] Output: [2, 4]
print("None")
2) Doubly Linked List
# Using the linked list
Inorder (Left → Root → Right)
LL = LinkedList() • Each node has two pointers:
[Link](10) 2) map() o next node Visit:
[Link](20) o previous node
[Link](30) Used to apply a function to each element of a sequence. • d, b, a, g, e, c, h, f, i
[Link]() Allows traversal in both directions.
Syntax: Inorder: d b a g e c h f i
None ← A ↔ B ↔ C → None
Output: map(function, sequence)
1) DFS – Depth First Search if is_prime: Write for each vertex the list of nodes it points to: lst[0:2] = [1, 2] # replace first two elements
print(num, "is a prime number") # [1, 2, 99, 30, 40, 50, 60]
else:
• Goes deep into the graph before backtracking. • 1: 2, 3
print(num, "is not a prime number")
• Uses Stack (can be implemented using recursion). • 2: 1, 3 So, updating a list means changing, inserting, or adding elements using index, append(), insert(),
• 3: 4 extend(), or slicing.
This program:
Idea: • 4: 1
• Printer task management square = lambda x: x*x Datatypes define the type of data a variable can store. Python supports several built-in datatypes:
print(square(5)) 4) Mapping Types
Output: 25 a) Dictionary (dict)
example. [4]
Mutable.
2) Lambda with multiple arguments • int → whole numbers
Example: 10, -5 Example: {"name": "Raj", "age": 20}
add = lambda a, b: a + b • float → decimal numbers
List comprehension is a short, compact, and elegant way to create lists in Python. print(add(3, 7)) Example: 3.14
• complex → numbers with real and imaginary part
General Syntax: Output: 10 Example: 3 + 5j
5) Boolean Type
new_list = [expression for item in iterable if condition]
• Represents True or False.
Example 1: Create a list of squares • Used for conditions.
3) Lambda with no argument 2) Sequence Types
squares = [x*x for x in range(1, 6)] Example:
print(squares) hello = lambda : "Hello World"
print(hello()) a) String (str) is_active = True
Output:
[1, 4, 9, 16, 25] • Collection of characters enclosed in quotes.
4) Lambda inside map() • Immutable.
Example 2: Get only even numbers 6) None Type
nums = [1, 2, 3, 4] Example: "Hello"
double = list(map(lambda x: x*2, nums))
evens = [x for x in range(10) if x % 2 == 0] Represents no value or null.
print(evens) b) List (list)
Output: [2, 4, 6, 8]
Example:
Output: • Ordered, mutable collection. x = None
[0, 2, 4, 6, 8] • Allows duplicate values.
Syntax:
• Database indexing
Searching is the process of finding an element in a data structure. Substitute A and B: Example:
• File search in OS
• Dictionary lookup age = 20
• AI path finding Postfix: if age >= 18:
• Data analysis print("Eligible to vote")
1) Linear Search pθ*Rs/+7-
numbers = [10, 20, 30] 3) discard() 1) Using key A Queue is a linear data structure that works on FIFO (First In First Out) principle.
[Link](40)
print(numbers)
The element inserted first is removed first.
Removes element but does not give error if element is missing. print(d["name"])
Syntax: if queue:
6) difference() print("Front element:", queue[0])
(Other possible operations: pop(), remove(), extend(), sort(), reverse())
lambda arguments : expression
Returns elements present in first set but not in second.
Used for converting infix → postfix and evaluating expressions. 2) Preorder Traversal (Root → Left → Right) • Complex data types used for better data handling.
4) Backtracking 22 12 8 20 30 25 40 Examples: Lists, Tuples, Stacks, Queues, Trees, Graphs 1) Adjacency Matrix
Used in maze solving, puzzles, DFS in graphs. • Uses a 2D matrix of size V × V (V = number of vertices)
3) Postorder Traversal (Left → Right → Root) Summary:
• 1means edge exists, 0 means no edge
5) Memory Management
Example:
8 20 12 25 40 30 22
Local variables and return addresses stored on stack. Category Examples Vertices: A, B, C
a) Define Data Structure. Explain the types of Data Structure. [4] Linear Array, Stack, Queue, Linked List
ABC
Non-Linear Tree, Graph
Data Structure: A0 1 0
Primitive int, float, char
b) Write a Python program to find factorial of a number. [4] A data structure is a method of organizing and storing data in a computer so that it can be used efficiently.
Non-Primitive lists, sets, tuples
B1 0 1
C0 1 0
Program:
Advantages:
Types of Data Structures: b) Write a Python program for queue using array. [4]
num = int(input("Enter a number: "))
• Easy to check whether an edge exists
if num < 0: 1) Linear Data Structures (Here array is implemented using Python list.)
• Good for dense graphs
print("Factorial does not exist for negative numbers")
else: queue = []
fact = 1 • Data is arranged sequentially (one after another). Disadvantages:
for i in range(1, num + 1): • Traversal happens in a single level. # Enqueue operation
fact *= i def enqueue(item): • Requires more memory (V²)
print("Factorial of", num, "is", fact) Examples: [Link](item)
print(item, "inserted")
This program multiplies numbers from 1 to n to find the factorial. • Array # Dequeue operation
• Linked List def dequeue(): 2) Adjacency List
• Stack if len(queue) == 0:
• Queue print("Queue is empty")
else: • Each vertex keeps a list of its neighbors
print("Deleted:", [Link](0)) • Uses linked list or list of lists
Features:
a) Compare between BFS and DFS traversal. [6]
x > 5 and x < 20
1. insert_front(x) – insert x at front
• Grows/shrinks at runtime 2. insert_rear(x) – insert x at rear
• Efficient insertion and deletion 3. delete_front() – remove item from front
Feature BFS (Breadth First Search) DFS (Depth First Search) 4) Assignment Operators
• Memory used only when needed 4. delete_rear() – remove item from rear
Working Level-by-level traversal Goes deep before backtracking isEmpty() – check if empty
• Access is slower (no index) 5.
principle Used to assign values.
6. display() – show elements
Data structure Queue Stack / Recursion
used Examples:
Starting point Starts from root and visits all Starts from root and explores one path =, +=, -=, *=, /=
neighbors first completely
Comparison Table
Shortest path Finds shortest path in an unweighted Does NOT always find shortest path Applications of Deque a = 10
Feature Static (Array) Dynamic (Pointer) a += 5 # 15
graph
Memory usage High (stores many nodes in queue) Low (only current path stored) Memory Fixed Flexible • Browser history (forward/backward)
Suitable for Trees/Graphs where nearest solution Tree/Graph where deeper solution needed Size change Not possible Possible anytime • Undo/redo operations
needed • Palindrome checking 5) Membership Operators
Insertion Slow Fast
Traversal nature Horizontal movement Vertical movement • Job scheduling
Deletion Slow Fast • Implementing both stacks and queues Used to check membership in sequences.
Storage Contiguous Non-contiguous
Example (Simple idea):
a) Explain various operators in Python
Examples:
in, not in
• BFS → Visit nodes in levels: 1 → 2 → 3 → 4
• DFS → Visit nodes deep: 1 → 2 → 5 → 6 → backtrack → 3
c) Explain the concept of Doubly Ended Queue programming. [4] 5 in [1,2,3,5] # True
(Deque). [6] Python provides different categories of operators used for calculations, comparisons, and logical operations.
6) Identity Operators
b) Explain the static and dynamic representation A Doubly Ended Queue (Deque) is a queue where insertion and deletion can occur from both ends
Check if two variables refer to the same object.
of Linked List. [6]
(front and rear).
1) Arithmetic Operators
Key Features: Examples:
Used for mathematical calculations. is, is not
Static Representation
• Supports enqueue and dequeue from: a is b
c) Write a Python program to print factorial of a
Age: 20
2) Deletion
7) Bitwise Operators Remove an element from the array.
b) What is List? State any four built-in list given number. [4]
Used on bits.
functions with their use. [4]
[Link](20)
Program:
Examples:
&, |, ^, <<, >> num = int(input("Enter a number: "))
3) Accessing Elements (optional) List:
if num < 0:
print("Factorial not possible for negative numbers")
Retrieve element using index. A list is a mutable, ordered collection in Python that can store different types of data. else:
intersection Python. [4] Adds an item at the end of the list. In Python, arguments are passed to functions using a model called “pass by object reference” (also called
call by sharing).
[Link](40)
Example Set: Class: To understand it simply:
s = {1,2,3}
A class is a blueprint or template for creating objects. 2) insert() • If you pass an immutable object (like int, float, string, tuple) → it behaves like pass by value
It contains variables (attributes) and functions (methods). (original is not changed).
Example Dictionary: Inserts an item at a specific index. • If you pass a mutable object (like list, dict, set) → it behaves like pass by reference (changes
d = {"id": 101, "name": "Amit"} Object: inside function affect original).
[Link](1, 15)
An object is an instance of a class, created using the class name. Example with immutable (int):
b) What is Queue? Explain types of Queue. [4] Order: Operator → Left → Right
3) peek() — View top element position of Linked List. [4]
• P * Q→* P Q
Queue (Definition)
• R * S→* R S Returns the top element without removing it. Python Program:
• Combine with + → + (* P Q) (* R S)
A Queue is a linear data structure that works on FIFO (First In First Out) principle. top = stack[-1] class Node:
Element inserted first is removed first. def __init__(self, data):
Prefix: [Link] = data
+ * P Q * R S
4) isEmpty() — Check if stack is empty
[Link] = None
Types of Queue:
class LinkedList:
Checks whether the stack has elements. def __init__(self):
[Link] = None
Postfix (Reverse Polish Notation) if len(stack) == 0:
1) Simple / Linear Queue # insert at start
print("Stack is empty")
Order: Left → Right → Operator def insert_start(self, data):
• Insertion (enqueue) at rear new_node = Node(data)
• Deletion (dequeue) from front new_node.next = [Link] # link new node to old head
→P Q *
b) Write the elements in BFS and DFS of the
• P * Q [Link] = new_node # update head
• Example: Line of people at ticket counter
• R * S→R S *
Combine with + at end → P Q * R S * +
following Binary Tree. [4]
• # display list
def display(self):
temp = [Link]
Postfix: while temp:
2) Circular Queue P Q * R S * + print([Link], end=" -> ")
Given Tree:
temp = [Link]
•
a) What is stack? Explain any four stack
Last position connects back to first position. print("None")
• Solves space wastage of simple queue. • 1 → 2, 3
• 2 → 4, 5 # Using the Linked List
1, 2, 3, 4, 5, 6, 7 Given tree:
c) Write Prefix and Postfix Expression of P * Q + R * S . [4] 1) push() — Insert element • 1 → 2, 3
Given infix expression: • 2 → 4, 5
Adds an element to the top of the stack.
DFS (Preorder Traversal: Root → Left → Right) • 3 → 6, 7
𝑃∗𝑄+𝑅∗𝑆 stack = []
[Link](10) # push 1, 2, 4, 5, 3, 6, 7 Tree Structure
This is: 1
/ \
2) pop() — Remove top element 2 3
(𝑃 ∗ 𝑄) + (𝑅 ∗ 𝑆) / \ / \
Removes the element at the top. 4 5 6 7
1) Inorder (Left → Root → Right) c) Explain any two ways of representation of a) What is Python? What are the benefits of using 6) Strong Community Support
Traversal:
4251637
graph. [4] Python? [6 Marks] Millions of developers contribute to Python packages, tutorials, and libraries.
Example:
3) Postorder (Left → Right → Root)
1) Easy to Learn and Read
Traversal:
For vertices A, B, C: Python has simple English-like syntax, making coding and understanding easier. b) What are the common built-in data types in
4526731 ABC Python? [6 Marks]
A0 1 0
B1 0 1 2) Interpreted Language Python has several built-in data types used to store different kinds of values.
Advantages
stack = []
1) Numeric Types
# Push operation • Easy to check if an edge exists. 3) Large Standard Library
def push(item): • Simple representation. • int → whole numbers
[Link](item)
Provides many built-in modules like: • float → decimal values
print("Pushed:", item)
Disadvantages • complex → numbers with real & imaginary part
# Pop operation • math
def pop_item(): • Requires more memory (V² space). • datetime a = 10
b = 3.14
if not stack: • random c = 2 + 5j
print("Stack is empty") • os
else:
• json
print("Popped:", [Link]())
# Peek operation
2) Adjacency List These reduce development time. 2) Sequence Types
def peek():
if not stack: • Each vertex stores a list of its neighbours.
String (str)
print("Stack is empty") • Implemented using list or linked list.
else:
print("Top element:", stack[-1]) 4) Portable and Platform Independent A sequence of characters. Immutable.
Example:
# Display stack name = "Python"
def display(): A → B
Python runs on Windows, Mac, Linux without changing the code.
print("Stack:", stack) B → A, C
C → B List (list)
# Using the stack
push(10) Ordered and mutable collection.
push(20) Advantages 5) Supports Multiple Programming Paradigms
push(30)
colors = ["red", "blue", "green"]
display() • Uses less memory. • Object-Oriented
peek() • Efficient for sparse graphs. • Functional
pop_item()
• Procedural Tuple (tuple)
display()
Disadvantages
Ordered and immutable.
• Checking the existence of a specific edge is slower.
4) Mapping Type
2) Doubly Linked List
Dictionary (dict)
Each node has two pointers:
Stores data in key–value pairs.
• to the next node
student = {"name": "Amit", "age": 20} • to the previous node
None ← A ↔ B ↔ C → None
• data
• Supports two-way circular movement
• pointer to the next node