Class 12 Computer Science (Python) – Chapter 3 Lists Manipulation and Implementation
This chapter introduces students to the concept of lists in Python, a fundamental data structure used to store and manipulate multiple items. Lists are ordered, mutable, and versatile, allowing you to store different types of data and manipulate them efficiently. Through this chapter, students will learn how to perform various list operations such as:
- Creating and accessing lists
- Modifying list elements
- Using list methods for adding, removing, and sorting elements
- List slicing and comprehensions for more concise and efficient code
- Working with nested lists and applying advanced techniques like sorting and searching
By the end of this chapter, students will be able to implement and manipulate lists to solve practical problems, understand the internal workings of list operations, and write efficient Python code for real-world applications.
Learning Objectives:
- Understand the concept and characteristics of lists in Python.
- Master basic list operations like addition, removal, and access of elements.
- Learn list slicing and comprehend how to create lists using list comprehension.
- Implement sorting, searching, and handling nested lists in Python programs.
This chapter is crucial as it forms the foundation for many algorithms and problem-solving strategies used in Python programming. Mastery of lists will prepare you for more complex data structures and algorithm implementation in later chapters.
What You Will Learn in Chapter 3 – Lists Manipulation and Implementation
This chapter will help you master list manipulations, including:
- Adding, removing, and accessing elements in a list.
- Sorting and searching techniques.
- Slicing and list comprehension for more efficient coding.
- Nested lists and their practical applications.
By the end of this chapter, you will be proficient in implementing various algorithms that involve list operations, such as sorting and searching, and understand how to use lists to store and manipulate data effectively.
Key Topics Covered:
Introduction to Lists
A list is a collection data type that allows storing multiple items in a single variable. In Python, lists are ordered, mutable, and can store items of different types. Lists are defined using square brackets, and the items inside the list are separated by commas.
# Example of a List:
my_list = [1, 2, 3, 4, 5]
Basic List Operations
1. Accessing Elements
Lists are indexed starting from 0. You can access elements using the index.
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Output: 1
2. Modifying Elements
Lists are mutable, meaning you can modify elements after they are created.
my_list[2] = 10 # Modifies element at index 2
print(my_list) # Output: [1, 2, 10, 4, 5]
3. Adding Elements
You can add elements using the append()
, insert()
, and extend()
methods.
my_list.append(6) # Adds 6 to the end
my_list.insert(2, 7) # Inserts 7 at index 2
my_list.extend([8, 9]) # Adds multiple elements at the end
4. Removing Elements
You can remove elements using the remove()
, pop()
, and clear()
methods.
my_list.remove(7) # Removes the first occurrence of 7
my_list.pop(2) # Removes element at index 2
my_list.clear() # Clears all elements from the list
5. Slicing Lists
Slicing allows you to extract a portion of a list.
my_list = [1, 2, 3, 4, 5]
sub_list = my_list[1:4] # Extracts elements from index 1 to 3
print(sub_list) # Output: [2, 3, 4]
Advanced List Operations
1. List Comprehension
A concise way to create lists based on existing lists, including conditional logic.
squares = [x ** 2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
2. Sorting Lists
Lists can be sorted using the sort()
method for in-place sorting or the sorted()
function for a new sorted list.
my_list = [3, 1, 4, 2, 5]
my_list.sort() # In-place sorting
print(my_list) # Output: [1, 2, 3, 4, 5]
3. Searching in Lists
You can use the in
keyword or the index()
method to search for elements in a list.
if 3 in my_list:
print(\"3 is in the list\")
4. Nested Lists
A list can contain other lists as elements. You can use indexing to access sub-lists or individual elements.
nested_list = [[1, 2], [3, 4], [5, 6]]
print(nested_list[1][0]) # Output: 3
NCERT Solutions for Chapter 3 – Lists Manipulation and Implementation
Intext Questions:
Definitions and Explanations:
1. What is a list in Python?
A list is a collection of ordered items. It is mutable, allowing elements to be modified, added, or removed. Lists are defined by placing elements inside square brackets, separated by commas.
2. Explain list slicing with an example.
List slicing is the process of extracting a portion of a list by specifying a range of indices. For example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # Output: [2, 3, 4]
3. What is list comprehension?
List comprehension provides a concise way to create lists by applying an expression to each item in an existing list or range. It can also include conditional logic.
squares = [x ** 2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
4. How do you search for an element in a list?
You can search for an element using the in
operator or the index()
method.
if 4 in my_list:
print(\"4 is in the list\")
Concepts and Syntax:
1. Explain how to sort a list in Python.
To sort a list in Python, use the sort()
method for in-place sorting, or use the sorted()
function to return a new sorted list.
2. Write a Python program to find the largest and smallest element in a list.
my_list = [10, 20, 4, 45, 99]
print(\"Largest element:\", max(my_list))
print(\"Smallest element:\", min(my_list))
Exercise Questions (Q1–Q8):
Detailed Answers:
1. Example of list slicing in Python.
my_list = [10, 20, 30, 40, 50]
sub_list = my_list[2:5]
print(sub_list) # Output: [30, 40, 50]
2. Python program to reverse a list.
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list) # Output: [5, 4, 3, 2, 1]
3. Example of list comprehension.
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
Practical Programming Tasks:
- Write Python programs to implement list operations like append, remove, and sort.
- Create a program that checks whether a list is sorted.
- Write a Python program to implement nested lists and access specific elements.
Download Chapter 3 Solutions PDF – Lists Manipulation and Implementation
Get access to our free, comprehensive PDF containing:
- All NCERT intext and exercise solutions.
- Clear explanations of list operations.
- Step-by-step code examples for list manipulation.
- Exam-focused answers for both short and long questions.
Highlights of Our NCERT Solutions:
- Clear Explanations with real-world examples of list manipulations.
- Code Snippets for understanding the practical application of list operations.
- Step-by-Step Solutions breaking down list slicing, sorting, and list comprehension.
- Visual Aids like flowcharts for understanding list operations.
Recommended Preparation Tips:
- Practice with Lists: Get comfortable with list operations, especially slicing and list comprehension.
- Master Sorting and Searching: Implement sorting and searching algorithms to work with lists efficiently.
- Work on Nested Lists: Practice working with nested lists and accessing elements within them.
- Write Programs: Reinforce concepts by writing Python programs that manipulate lists.
Additional Study Resources:
- Flashcards for Key Terms (List, Append, Remove, Sort, etc.)
- Flowchart Practice Sheets for list operations.
- Past Year CBSE Questions on Lists.
- Online Quizzes and Mock Tests on list manipulations.
Mastering Chapter 3 – Lists Manipulation and Implementation
Mastering lists and their manipulations will give you a solid foundation for solving problems in Python. Lists are versatile and widely used in various programming tasks, so understanding how to work with them is crucial. Practice regularly to sharpen your skills and ensure you\’re ready for your CBSE Board Exams and competitive exams.
Class 12 Computer Science (Python) – Chapter 3 Lists Manipulation and Implementation
NCERT Textbook Questions Solved – Class 12 Computer Science (Python)
Question 1: Define a data structure.
A data structure is a collection of related data elements that can be processed as a single unit. These data elements can either be of the same or different data types. Data structures are vital in programming because they allow efficient organization and manipulation of large sets of data.
Question 2: Name the two types of data structures and give a difference between them.
Data structures can be classified into two main types: Linear and Non-Linear.
Linear Data Structure: The elements are stored in a sequential manner, where each element is connected to the previous and next one.
Non-Linear Data Structure: The elements are not stored sequentially, and the hierarchy is complex, with no linear order.
Examples:
Linear: Arrays, Lists, Stacks, Queues, Linked Lists
Non-Linear: Trees, Graphs
Question 3: Give a difference between an array and a list in Python.
An array in Python refers to a collection of elements of the same data type stored in contiguous memory locations. On the other hand, a list in Python can store elements of different data types, and its size is dynamic, meaning it can grow or shrink during runtime.
Question 4: How are lists implemented in memory?
In Python, a list is implemented using a dynamic array of references. Each element in the list is a reference (pointer) to the actual object, which allows the list to store objects of various data types. The list itself is stored in memory as an array of these references, and the list header keeps track of the array\’s length. When items are appended or inserted, the array dynamically resizes to accommodate new elements.
Question 5: What is sequential allocation of memory? Why do we say that lists are stored sequentially?
Sequential allocation refers to the process of storing elements in memory one after another, in the order of their declaration. This means that in a list, the elements are stored consecutively, so to access the fifth element, the first four must be traversed first. This is why lists in Python are said to be stored sequentially in memory.
TOPIC-2: Searching Lists
Question 1: How is linear search different from binary search?
Linear Search: It searches for an element in a sequential manner and works on both sorted and unsorted lists. It has a time complexity of O(n).
Binary Search: This search method only works on sorted data and divides the search interval in half after each comparison. Its time complexity is O(log n), making it faster than linear search for large datasets.
Short Answer Type Questions-I (2 marks)
Question 1: Accept a list containing integers randomly. Accept any number and display the position at which the number is found in the list.
maxrange = int(input(\"Enter count of numbers: \")) marks = [] flag = False for i in range(maxrange): marks.append(int(input(\"Enter number: \"))) number = int(input(\"Enter number to be searched: \")) for i in range(maxrange): if marks[i] == number: print(number, \"found at position\", i) flag = True if not flag: print(number, \"not found in list\")
Question 2: What will be the status of the following list after the First, Second, and Third pass of the selection sort method used for arranging the following elements in descending order?
List: 12, 14, -54, 64, 90, 24
First pass: [90, 14, -54, 64, 12, 24] (largest element 90 is swapped with the first element)
Second pass: [90, 64, -54, 14, 12, 24] (largest of the remaining elements 64 swapped with second element)
Third pass: [90, 64, 24, 14, 12, -54] (largest of the remaining elements 24 swapped with third element)
Question 3: For a given list of values in descending order, write a method in Python to search for a value with the help of Binary search method. The method should return the position of the value and should return -1 if the value is not present in the list.
def binary_srch(nums, x): low = 0 high = len(nums) - 1 while low <= high: mid = (low + high) // 2 mid_val = nums[mid] if mid_val == x: return mid elif mid_val < x: high = mid - 1 else: low = mid + 1 return -1
TOPIC-3: List Sorting
Question 1: What is bubble sort?
Bubble sort is a simple comparison-based sorting algorithm. It repeatedly steps through the list, comparing adjacent items and swapping them if they are in the wrong order. This process is repeated until the list is sorted. The algorithm is called bubble sort because smaller elements “bubble” to the top of the list with each pass.
Question 2: Write an algorithm for selection sort.
Selection sort works as follows:
- Start from the first index (0).
- Find the smallest (or largest) element in the remaining unsorted part of the list.
- Swap the smallest (or largest) element found with the element at the current index.
- Repeat the process for the next index until the entire list is sorted.
Question 3: Explain insertion sort.
Insertion sort works by taking each element from the input data and placing it in its correct position in the already-sorted part of the list. It compares the current element with those before it and shifts the larger elements to the right to create space for the current element.
Short Answer Type Questions-II (2 marks)
Question 1:
Write a function that takes a list that is sorted in ascending order and a number as argument. The function should do the following:
- Insert the number passed as argument in a sorted list.
- Delete the number from the list.
Answer:
from bisect import bisect
def listfunc(sortedlist, number):
insert_point = bisect(sortedlist, number)
sortedlist.insert(insert_point, number)
print(\"List after Insertion:\", sortedlist)
sortedlist.remove(number)
print(\"List after Deletion:\", sortedlist)
maxrange = int(input(\"Enter Count of numbers: \"))
numlist = []
for i in range(maxrange):
numlist.append(int(input(\"? \")))
numlist.sort()
number = int(input(\"Enter the number: \"))
listfunc(numlist, number)
Question 2:
Consider the following list 95 79 19 43 52 3
Write the passes of bubble sort sorting the list in ascending order till the 3rd iteration.
Answer:
- Pass 1: [79, 19, 43, 52, 3, 95]
- Pass 2: [19, 43, 52, 3, 79, 95]
- Pass 3: [19, 43, 3, 52, 79, 95]
Question 3:
Write a function that takes a sorted list and a number as an argument. Search for the number in the sorted list using binary search.
Answer:
def binary_search(SORTEDLIST, number):
low = 0
high = len(SORTEDLIST) - 1
found = False
while low <= high and not found:
mid = (low + high) // 2
if SORTEDLIST[mid] == number:
print(\"Number found at index\", mid)
found = True
elif SORTEDLIST[mid] < number:
low = mid + 1
else:
high = mid - 1
if not found:
print(\"Number not found\")
maxrange = int(input(\"Enter Count of numbers: \"))
numlist = []
for i in range(maxrange):
numlist.append(int(input(\"? \")))
numlist.sort()
print(\"Sorted list:\", numlist)
number = int(input(\"Enter the number: \"))
binary_search(numlist, number)
Question 4:
In the following list containing integers, sort the list using Insertion sort algorithm. Also show the status of the list after each iteration.
List: 15 -5 20 -10 10
Answer:
def insertion_sort(DATA_LIST):
for K in range(1, len(DATA_LIST)):
temp = DATA_LIST[K]
ptr = K - 1
while ptr >= 0 and DATA_LIST[ptr] > temp:
DATA_LIST[ptr + 1] = DATA_LIST[ptr]
ptr -= 1
DATA_LIST[ptr + 1] = temp
print(DATA_LIST)
DATA_LIST = [15, -5, 20, -10, 10]
print(\"LIST BEFORE SORTING:\", DATA_LIST)
insertion_sort(DATA_LIST)
- Pass 1: [-5, 15, 20, -10, 10]
- Pass 2: [-5, 15, 20, -10, 10]
- Pass 3: [-10, -5, 15, 20, 10]
- Pass 4: [-10, -5, 10, 15, 20]
Question 5:
What will be the status of the following after the First, Second and Third pass of the insertion sort method used for arranging the following elements in descending order?
Note: Show the status of all the elements after each pass very clearly underlining the changes.
Answer:
- Pass 1: [34, 12, 46, -34, 90, 23]
- Pass 2: [46, 34, 12, -34, 90, 23]
- Pass 3: [90, 46, 34, 12, -34, 23]
Question 6:
Consider the following unsorted list:
99 78 25 48 51 11
Sort the list using selection sort algorithm. Show the status of the list after every iteration.
Answer:
def selection_sort(DATA_LIST):
for i in range(len(DATA_LIST)):
min_index = i
for j in range(i + 1, len(DATA_LIST)):
if DATA_LIST[j] < DATA_LIST[min_index]:
min_index = j
DATA_LIST[i], DATA_LIST[min_index] = DATA_LIST[min_index], DATA_LIST[i]
print(DATA_LIST)
DATA_LIST = [99, 78, 25, 48, 51, 11]
print(\"LIST BEFORE SORTING:\", DATA_LIST)
selection_sort(DATA_LIST)
Question 7:
Consider the following unsorted list: Neena Meeta Geeta Reeta Seeta
Sort the list using selection sort algorithm. Show the status of the list after every iteration.
(or)
Sort a list containing names of students in ascending order using selection sort.
Answer:
def selection_sort(DATA_LIST):
for i in range(len(DATA_LIST)):
min_index = i
for j in range(i + 1, len(DATA_LIST)):
if DATA_LIST[j] < DATA_LIST[min_index]:
min_index = j
DATA_LIST[i], DATA_LIST[min_index] = DATA_LIST[min_index], DATA_LIST[i]
print(DATA_LIST)
NAME_LIST = [\'Neena\', \'Beeta\', \'Reeta\', \'Geeta\', \'Seeta\']
print(\"LIST BEFORE SORTING:\", NAME_LIST)
selection_sort(NAME_LIST)
- Pass 1: [\’Beeta\’, \’Neena\’, \’Reeta\’, \’Geeta\’, \’Seeta\’]
- Pass 2: [\’Beeta\’, \’Geeta\’, \’Reeta\’, \’Neena\’, \’Seeta\’]
- Pass 3: [\’Beeta\’, \’Geeta\’, \’Neena\’, \’Reeta\’, \’Seeta\’]
- Pass 4: [\’Beeta\’, \’Geeta\’, \’Neena\’, \’Reeta\’, \’Seeta\’]
- Pass 5: [\’Beeta\’, \’Geeta\’, \’Neena\’, \’Reeta\’, \’Seeta\’]
Question 8:
A list contains rollno, name and marks of the student. Sort the list in descending order of marks using selection sort algorithm.
Answer:
def selection_sort(DATA_LIST):
for i in range(len(DATA_LIST)):
max_index = i
for j in range(i + 1, len(DATA_LIST)):
if DATA_LIST[j][2] > DATA_LIST[max_index][2]:
max_index = j
DATA_LIST[i], DATA_LIST[max_index] = DATA_LIST[max_index], DATA_LIST[i]
print(DATA_LIST)
maxrange = int(input(\"Enter Number of Students: \"))
Students = []
for i in range(maxrange):
roll = input(\"Enter roll_no: \")
name = input(\"Enter name: \")
marks = int(input(\"Enter marks: \"))
Students.append([roll, name, marks])
print(\"Original List:\", Students)
selection_sort(Students)
Question 9:
What will be the status of the following list after the First, Second and Third pass of the insertion sort method used for arranging the following elements in descending order?
Elements: 12, 34, 46, -34, 90, 23
Note: Show the status of all the elements after each pass very clearly underlining the changes.
Answer:
- Pass 1: [34, 12, 46, -34, 90, 23]
- Pass 2: [46, 34, 12, -34, 90, 23]
- Pass 3: [90, 46, 34, 12, -34, 23]
Long Answer Type Questions (4 Marks)
Question 1:
Consider the following unsorted list: 90, 78, 20, 46, 54, 1. Write the list after:
- 3rd iteration of selection sort
- 4th iteration of bubble sort
- 5th iteration of insertion sort
Answer:
Sorting Technique | State of List |
---|---|
3rd iteration of Selection Sort | [1, 20, 46, 78, 54, 90] |
4th iteration of Bubble Sort | [1, 20, 46, 54, 90, 78] |
5th iteration of Insertion Sort | [1, 20, 46, 54, 78, 90] |
Question 2:
Consider the following unsorted list: 10, 5, 55, 13, 3, 49, 36. Write the list after:
- (i) 5th iteration of Bubble Sort
- (ii) 7th iteration of Insertion Sort
- (iii) 4th iteration of Selection Sort
Answer:
Iteration | Result |
---|---|
5th iteration of Bubble Sort | [3, 5, 10, 13, 36, 55, 49] |
7th iteration of Insertion Sort | Not possible – list has only 7 elements |
4th iteration of Selection Sort | [3, 5, 10, 13, 55, 49, 36] |
Question 3:
Write a class CITY
in Python with the following specifications:
- CName – City Name (String)
- Pop – Population (Numeric)
- KM – Area in square km (Numeric)
- Ccode – City Code (Numeric)
- Density – Population Density (Numeric, calculated as Pop/KM)
Methods:
DenCal()
– Calculates density as Pop/KMRecord()
– Allows user input for Ccode, CName, Pop, KM and calculates densityView()
– Displays all values and shows \”Highly Populated City\” if density > 10,000
Answer (Python Code):
class CITY:
def __init__(self):
self.Ccode = 0
self.CName = \"\"
self.Pop = 0
self.KM = 0
self.Density = 0
def DenCal(self):
self.Density = self.Pop / self.KM
def Record(self):
self.Ccode = int(input(\"Enter City Code: \"))
self.CName = input(\"Enter City Name: \")
self.Pop = int(input(\"Enter Population: \"))
self.KM = float(input(\"Enter Area in KM: \"))
self.DenCal()
def View(self):
print(\"Code:\", self.Ccode)
print(\"Name:\", self.CName)
print(\"Population:\", self.Pop)
print(\"Area (KM):\", self.KM)
print(\"Density:\", self.Density)
if self.Density > 10000:
print(\"Highly Populated City\")
Question 4:
A list contains Item_code
, Item_name
, qty
, and price
. Sort the list:
- In ascending order of qty using Bubble Sort.
- In descending order of price using Insertion Sort.
Answer (Python Code):
def bubble_sort(items):
n = len(items)
print(\"Bubble Sort – Ascending Order of Quantity\")
for i in range(n):
for j in range(0, n - i - 1):
if items[j][3] > items[j + 1][3]:
items[j], items[j + 1] = items[j + 1], items[j]
print(\"Step\", i + 1, \":\", items)
def insertion_sort(items):
print(\"Insertion Sort – Descending Order of Price\")
for i in range(1, len(items)):
key = items[i]
j = i - 1
while j >= 0 and items[j][2] < key[2]:
items[j + 1] = items[j]
j -= 1
items[j + 1] = key
print(\"Step\", i, \":\", items)
items = []
n = int(input(\"Enter number of items: \"))
for _ in range(n):
code = input(\"Enter Item Code: \")
name = input(\"Enter Item Name: \")
price = float(input(\"Enter Price: \"))
qty = int(input(\"Enter Quantity: \"))
items.append([code, name, price, qty])
print(\"Before Sorting:\", items)
bubble_sort(items)
insertion_sort(items)
TOPIC-4
Stacks And Queues With Lists
Very Short Answer Type Questions (1 mark)
Short Answer Type Questions (1 Mark)
Question 1:
Expand the following:
Abbreviation | Full Form |
---|---|
LIFO | Last-In First-Out |
FIFO | First-In First-Out |
Question 2:
Define stack.
A stack is a linear data structure that follows the Last-In First-Out (LIFO) principle. Elements are added and removed from the top of the stack.
Question 3:
Define Queue.
A queue is a linear data structure that follows the First-In First-Out (FIFO) principle. Elements are inserted at the rear and deleted from the front.
Question 4:
Write all the operations possible in a data structure.
Operation | Description |
---|---|
Traversal | Visiting all elements of the data structure |
Insertion | Adding a new element |
Deletion | Removing an existing element |
Searching | Finding an element in the data structure |
Question 5:
What are the two major queue operations?
Operation | Description |
---|---|
Enqueue | Inserts element at the rear of the queue |
Dequeue | Deletes element from the front of the queue |
Short Answer Type Questions-I (2 Marks)
Question 1:
Write an algorithm to implement push operation.
Algorithm Push(stack, top, item) 1. Start 2. Increment top by 1 3. Set stack[top] = item 4. Print \"Item Inserted\" 5. Stop
Question 2:
Write an algorithm to implement pop operation.
Algorithm Pop(stack, top) 1. Start 2. If top == -1 Print \"Stack Empty\" Go to Step 5 3. Set deleted_item = stack[top] 4. Decrement top by 1 5. Print \"Item Deleted\" 6. Stop
Question 3:
Write an algorithm to implement insertion operation of queue.
Algorithm Enqueue(queue, front, rear, item) 1. Start 2. If front == -1 and rear == -1 Set front = rear = 0 Else Increment rear by 1 3. queue[rear] = item 4. Stop
Question 4:
Write an algorithm to implement deletion operation of queue.
Algorithm Dequeue(queue, front, rear) 1. Start 2. If front == -1 Print \"Queue Underflow\" Stop 3. Set deleted_item = queue[front] 4. If front == rear Set front = rear = -1 Else Increment front by 1 5. Print \"Item Deleted\" 6. Stop
Question 5:
Write a Python method to perform Binary Search on a sorted list.
def binary_search(arr, search):
lower = 0
upper = len(arr) - 1
while lower <= upper:
mid = (lower + upper) // 2
if arr[mid] == search:
return mid # Item found at index mid
elif search < arr[mid]:
upper = mid - 1
else:
lower = mid + 1
return -1 # Item not found
Long Answer Type Questions (4 Marks)
Question 1:
Write Insert(city) and Delete(city) methods in Python using queue.
class Queue:
def __init__(self):
self.city = []
def insert(self):
city_name = input(\"Enter city: \")
self.city.append(city_name)
print(\"City inserted:\", city_name)
def delete(self):
if not self.city:
print(\"Queue is empty\")
else:
deleted = self.city.pop(0)
print(\"Deleted city:\", deleted)
Question 2:
Define Stack class in Python to operate on a stack of numbers.
class Stack:
def __init__(self):
self.stack = []
def push(self):
num = int(input(\"Enter number: \"))
self.stack.append(num)
print(\"Number pushed:\", num)
def pop(self):
if not self.stack:
print(\"Stack is empty\")
else:
popped = self.stack.pop()
print(\"Number popped:\", popped)
def display(self):
if not self.stack:
print(\"Stack is empty\")
else:
print(\"Stack elements (top to bottom):\")
for i in range(len(self.stack)-1, -1, -1):
print(self.stack[i])
Question 3:
Write a function to push any student’s information to stack.
def push(stack):
student = []
print(\"STACK BEFORE PUSH\")
display(stack)
student.append(int(input(\"Enter student roll number: \")))
student.append(input(\"Enter student name: \"))
student.append(input(\"Enter student grade: \"))
stack.append(student)
def display(stack):
print(\"STACK CONTENTS:\")
for i in range(len(stack) - 1, -1, -1):
print(stack[i])
stack = []
n = int(input(\"Enter the number of students: \"))
for i in range(n):
student = []
student.append(int(input(\"Enter student roll number: \")))
student.append(input(\"Enter student name: \"))
student.append(input(\"Enter student grade: \"))
stack.append(student)
push(stack)
display(stack)
Question 4:
Write the push operation of stack containing names using class.
class Stack:
s = []
def push(self):
name = input(\"Enter any name: \")
Stack.s.append(name)
def display(self):
print(\"STACK CONTENTS:\")
for i in range(len(Stack.s) - 1, -1, -1):
print(Stack.s[i])
a = Stack()
n = int(input(\"Enter number of names: \"))
for i in range(n):
a.push()
a.display()
Question 5:
Write Insert (Place) and Delete (Place) methods to act as Queue operations.
class Queue:
place = []
def insert(self):
city = input(\"Enter city: \")
Queue.place.append(city)
def delete(self):
if not Queue.place:
print(\"Queue empty\")
else:
print(\"Deleted element is:\", Queue.place.pop(0))
q = Queue()
n = int(input(\"Enter number of cities: \"))
for i in range(n):
q.insert()
q.delete()
Question 6:
Write the pop operation of stack containing names using class.
class Stack:
s = []
def push(self):
name = input(\"Enter any name: \")
Stack.s.append(name)
def pop(self):
if not Stack.s:
print(\"Stack Empty\")
else:
print(\"Deleted element is:\", Stack.s.pop())
def display(self):
print(\"STACK CONTENTS:\")
for i in range(len(Stack.s) - 1, -1, -1):
print(Stack.s[i])
a = Stack()
n = int(input(\"Enter number of names: \"))
for i in range(n):
a.push()
a.pop()
a.display()
Question 7:
Write the pop operation of stack containing numbers using class.
class Stack:
s = []
def push(self):
num = int(input(\"Enter number: \"))
Stack.s.append(num)
def pop(self):
if not Stack.s:
print(\"Stack Empty\")
else:
print(\"Deleted element is:\", Stack.s.pop())
def display(self):
print(\"STACK CONTENTS:\")
for i in range(len(Stack.s) - 1, -1, -1):
print(Stack.s[i])
a = Stack()
n = int(input(\"Enter count of numbers: \"))
for i in range(n):
a.push()
a.pop()
a.display()
Question 8:
Write a function to add any customer’s information to queue.
def insert(queue):
customer = []
print(\"QUEUE BEFORE INSERT\")
display(queue)
customer.append(int(input(\"Enter customer number: \")))
customer.append(input(\"Enter customer name: \"))
customer.append(input(\"Enter customer phone number: \"))
queue.append(customer)
def display(queue):
print(\"QUEUE CONTENTS:\")
for i in range(len(queue)):
print(queue[i])
queue = []
n = int(input(\"Enter number of customers: \"))
for i in range(n):
customer = []
customer.append(int(input(\"Enter customer number: \")))
customer.append(input(\"Enter customer name: \"))
customer.append(input(\"Enter customer phone number: \"))
queue.append(customer)
insert(queue)
display(queue)
Question 9:
Write the insertion operation of queue containing characters using class.
class Queue:
s = []
def insert(self):
ch = input(\"Enter any letter: \")
Queue.s.append(ch)
def display(self):
print(\"QUEUE CONTENTS:\")
for item in Queue.s:
print(item)
q = Queue()
n = int(input(\"Enter number of letters: \"))
for i in range(n):
q.insert()
more = input(\"Do you want to insert more letters (y/n)? \")
if more.lower() == \'y\':
q.insert()
q.display()
Question 10:
Write Add(Fruit) and Remove(Fruit) methods using Queue logic.
def que_insert(fruit_list, rear):
while True:
fruit = input(\"Enter a fruit: \")
fruit_list.append(fruit)
rear += 1
ch = input(\"Do you want to add more (yes/no)? \").lower()
if ch == \'no\':
break
return rear
def que_delete(fruit_list, rear):
if not fruit_list:
print(\"Fruit list is empty\")
else:
removed = fruit_list.pop(0)
rear -= 1
print(\"Fruit deleted from list:\", removed)
return rear
fruits = []
rear = -1
rear = que_insert(fruits, rear)
rear = que_delete(fruits, rear)
Question 11:
Write the deletion operation of queue containing characters using class.
class Queue:
s = []
def insert(self):
ch = input(\"Enter any letter: \")
Queue.s.append(ch)
def delete(self):
if not Queue.s:
print(\"Queue Empty\")
else:
print(\"Deleted element is:\", Queue.s.pop(0))
def display(self):
print(\"QUEUE CONTENTS:\")
for item in Queue.s:
print(item)
q = Queue()
n = int(input(\"Enter number of letters: \"))
for i in range(n):
q.insert()
q.delete()
q.display()
Question 12:
Write the deletion operation of queue containing numbers using class.
class Queue:
s = []
def insert(self):
num = int(input(\"Enter number: \"))
Queue.s.append(num)
def delete(self):
if not Queue.s:
print(\"Queue Empty\")
else:
print(\"Deleted element is:\", Queue.s.pop(0))
def display(self):
print(\"QUEUE CONTENTS:\")
for item in Queue.s:
print(item)
q = Queue()
n = int(input(\"Enter number of numbers: \"))
for i in range(n):
q.insert()
q.delete()
q.display()
TOPIC-5
Applications of Stacks
Very Short Answer Type Questions (1 mark)
Question 1:
Evaluate the following postfix expression:12, 2, 7, 34, 20, -, +, 5, +
Status of Stack After Each Operation:
Operation | Stack Status |
---|---|
12 | [12] |
2 | [12, 2] |
7 | [12, 2, 7] |
34 | [12, 2, 7, 34] |
20 | [12, 2, 7, 34, 20] |
– | [12, 2, 7, 14] |
+ | [12, 2, 21] |
5 | [12, 2, 21, 5] |
+ | [12, 2, 26] |
Question 2:
Evaluate the postfix expression:2, 13, +, 5, -, 6, 3, /, 5, *, <
Result: 0
Question 3:
Evaluate using stack:10, 3, *, 30, 2, *, -
Result: 30
Question 4:
Evaluate the postfix expression:20, 10, -, 15, 3, /, +, 5, *
Result: 75
Question 5:
Convert the expression:A + (B * C – (D / E ^ F) * G) * H
into postfix form.
Answer:ABC*DEF^/G*-H*+
Question 6:
Convert (True AND False) OR (False AND True) into postfix form using stack:
Answer:True False AND False True AND OR
Question 7:
What are the applications of queue in computers?
- In multitasking operating systems, jobs waiting to be processed form a queue.
- Print jobs in shared printers follow the queue structure.
- Code compilation involves queued tasks.
- Download managers queue files for downloading.
- Job scheduling in multiuser environments uses queues.
Question 8:
Evaluate postfix expression:12, 2, *, 24, 20, -, +, 8, -
Result: 28
Question 9:
Evaluate postfix expression:12, 2, *, 24, 20, -, +, 8, -
Final Result: 28
Question 10:
Give few applications of stack:
- Expression evaluation
- Backtracking algorithms (e.g., maze solving, puzzles)
- Memory management
- Run-time environment for recursion
Short Answer Type Questions – II (3 Marks)
Question 1:
Write an algorithm to evaluate a postfix expression:
- Start
- Read the expression from left to right
- For each symbol in the expression:
- If the symbol is an operand, push it onto the stack.
- If the symbol is an operator:
- Pop top two operands from the stack
- Apply the operator
- Push the result back on the stack
- When expression ends, top of the stack is the result.
- Stop
Question 2:
Write an algorithm to convert infix to postfix:
- Initialize an empty stack and an empty postfix expression
- Scan the infix expression from left to right
- For each token:
- If it\’s an operand, add it to the postfix output
- If it\’s an operator:
- Pop all operators from stack with greater or equal precedence
- Add popped operators to the postfix output
- Push current operator to stack
- If \'(\’, push it to stack
- If \’)\’, pop and output until \'(\’ is found
- After scanning, pop and add remaining stack operators to postfix