[go: up one dir, main page]

100% found this document useful (1 vote)
48 views44 pages

Array Question Bank

The document provides a comprehensive question bank on arrays in Python, covering concepts such as the time trade-off, finding maximum and minimum values in arrays, list operations, and duplicate element handling. It includes code examples for various operations like sorting, inserting, and removing elements, as well as demonstrating the use of NumPy functions. Additionally, it explains the differences between aliasing, copying, and viewing arrays, along with methods to remove duplicates using different approaches.

Uploaded by

mishthijaiswal37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
48 views44 pages

Array Question Bank

The document provides a comprehensive question bank on arrays in Python, covering concepts such as the time trade-off, finding maximum and minimum values in arrays, list operations, and duplicate element handling. It includes code examples for various operations like sorting, inserting, and removing elements, as well as demonstrating the use of NumPy functions. Additionally, it explains the differences between aliasing, copying, and viewing arrays, along with methods to remove duplicates using different approaches.

Uploaded by

mishthijaiswal37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

MODULE - 5 ARRAYS QUESTION BANK

1. Provide examples that demonstrate the time trade-off concept in Python .


Answer) The time trade-off concept in Python refers to the balance between
computational time (execution speed) and other factors, such as memory usage or
simplicity of code.

● Sorting vs. Iteration Trade-Off

When searching for the minimum in an unsorted list multiple times, you can sort
the list once to save time during subsequent operations. However, sorting upfront
takes additional time.

Without Sorting (Simpler, Slower for Repeated Queries):


data = [5, 1, 9, 3, 7]

# Find the minimum multiple times


for _ in range(5):
print(min(data)) # O(n) per call

With Sorting (Faster for Repeated Queries):


data = [5, 1, 9, 3, 7]

# Sort the list once


data.sort() # O(n log n)
min_value = data[0]

# Reuse the minimum


for _ in range(5):
print(min_value) # O(1) per call

Trade-off: Sorting saves time during repeated queries but incurs an upfront cost.

● Using a Dictionary vs. List for Lookup Operations

When searching for items, dictionaries offer faster lookups but consume more
memory compared to lists.

Using a List (Slower Lookup, Less Memory):


data = [10, 20, 30, 40, 50]

# Check if an item exists

print(30 in data) # O(n) time complexity

Using a Dictionary (Faster Lookup, More Memory):

data = {10: True, 20: True, 30: True, 40: True, 50: True}

# Check if an item exists

print(30 in data) # O(1) time complexity

Trade-off:

● The list is simpler and uses less memory but has slower lookups.
● The dictionary speeds up lookups at the cost of increased memory usage.

2. Explain the way of Finding the Maximum number in an array and minimum
number from an ordered array with suitable example programs.

Answer) To find the maximum number in an array, we would follow the code below:

arr = [10,5, 7 , 13, 22] # Example array taken

max = arr[0]

for i in range (len(arr)):

if arr[i] > max:

max = arr[i]

print(“The maximum number is: ”, max)

To find the minimum number in an array, we would follow the code below:

arr = [10,5, 7 , 13, 22] # Example array taken

min = arr[0]
for i in range (len(arr)):

if arr[i] < min:

min = arr[i]

print(“The minimum number is: ”, min)

3. Illustrate the following function in python List with an example.

a) del

The del function in a list deletes the element by index or slice, or removes the
entire list.

Example:

my_list = [10, 20, 30, 40]

del my_list[1] # Deletes the element at index 1

print(my_list) # Output: [10, 30, 40]

b) remove

The remove function in Python removes the first occurrence of a specified value
from a list.

Example:

my_list = [10, 20, 30, 20, 40]

my_list.remove(20) # Removes the first occurrence of 20

print(my_list) # Output: [10, 30, 20, 40]

c) sort

The sort function in Python sorts the elements of a list in ascending or descending
order, modifying the original list in place.

Example:

my_list = [50, 10, 40, 20, 30]

my_list.sort() # Sorts in ascending order


print(my_list) # Output: [10, 20, 30, 40, 50]

d) insert

Insert function in python helps to insert or add an extra element at the specified
index number.

Example:

my_list = [10, 20, 30, 40]

my_list.insert(2, 25) # Inserts 25 at index 2

print(my_list) # Output: [10, 20, 25, 30, 40]

e) pop

Pop function in python is used to remove and return the element at a specified
index from the list. If no index is mentioned, it removes the last element.

Example:

my_list = [10, 20, 30, 40]

popped_value = my_list.pop(2) # Removes and returns the element at index 2 (30)

print(my_list) # Output: [10, 20, 40]

print("Popped value:", popped_value) # Output: Popped value: 30

4. Consider a 2D matrix a = [[1, 2, 3], [4, 5, 6],[7, 8, 9]] What will be the result of
the following slicing operations?

a[0] - [1,2,3]

a[1][2] - 6

a[0:2] - [[1,2,3], [4,5,6]]

a[1:] - [[4,5,6], [7,8,9]]

a[::2] - [[1,2,3], [7,8,9]]

Demonstrate rank(), ndim(), size(), shape() and reshape() functions on a matrix

These functions are typically used with NumPy arrays and not regular python lists.
Here is a python code explaining all the above functions:
import numpy as np

# Create a 2D matrix (3x3 array)

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# 1. rank() - returns the number of dimensions (same as ndim)

print("Rank of matrix (number of dimensions):", np.linalg.matrix_rank(a))

# 2. ndim() - returns the number of dimensions (axis count)

print("Number of dimensions (ndim):", a.ndim)

# 3. size() - returns the total number of elements

print("Total number of elements (size):", a.size)

# 4. shape() - returns a tuple representing the dimensions of the matrix

print("Shape of the matrix:", a.shape)

# 5. reshape() - changes the shape of the matrix (reshaping into a 1D array here)

reshaped_matrix = a.reshape(1, 9) # reshape the 3x3 matrix to a 1x9 matrix

print("Reshape matrix to 1x9:", reshaped_matrix)

5. Define arrays in python. Write Python code to count the total no. of duplicate
elements in array, remove the duplicate elements from the array, return the
number which has maximum duplicate elements

Definition of Array in Python:

In Python, an array is typically represented using a list. A list is an ordered,


mutable collection of elements that can be of any data type. Arrays in Python are
dynamic, meaning they can grow and shrink in size.

Python also has a pre-defined module associated with arrays for more complex
uses. But for simple operations, we use lists.

THE PYTHON CODE:

from collections import Counter


# Example array

arr = [1, 2, 3, 1, 4, 2, 5, 3, 1

# 1. Count the total number of duplicate elements

count_elements = Counter(arr)

duplicates_count = sum(1 for value in count_elements.values() if value > 1)

print("Total number of duplicate elements:", duplicates_count)

# 2. Remove the duplicate elements (retain only unique elements)

unique_elements = list(count_elements.keys())

print("Array with duplicates removed:", unique_elements)

# 3. Find the number with the maximum duplicate elements

max_duplicate_number = max(count_elements, key=count_elements.get)

print("The number with the maximum duplicate elements:",


max_duplicate_number)

6. Create various arrays using arrange () function and linspace()


function.Demonstrate the difference between alias, copy() and view() using an
example and its output.

The arrange() function in Numpy is used to create arrays with evenly spaced
values within a specified range

CODE: numpy.arange([start], stop, [step])

Example:

import numpy as np

arr = np.arange(1, 10, 2) # Start at 1, stop before 10, step by 2

print(arr) # Output: [1 3 5 7 9]

The linespace() function in Numpy is used to create an array with a specified


number of values only.
CODE: numpy.linspace(start, stop, num=50, endpoint=True, retstep=False,
dtype=None)

Example:

arr = np.linspace(1, 10, 5) # Start at 1, stop at 10, generate 5 values

print(arr) # Output: [ 1. 3.25 5.5 7.75 10. ]

Alias:

● An alias is just another name for the same array.


● Any changes made to the alias are reflected in the original array because
they share the same data and memory location.

View:

● A view creates a new array object that looks at the same data as the
original array.
● Changes in the view reflect in the original array, but their identities (objects)
are different.

Copy:

● A copy creates a new array with its own data.


● Changes in the copied array do not affect the original array and vice versa

Example:

import numpy as np

# Original array

original_array = np.array([1, 2, 3, 4, 5])

# Alias

alias_array = original_array # No new array is created

alias_array[0] = 100 # Modifies the original array as well

# View

view_array = original_array.view() # New array shares the same data buffer

view_array[1] = 200 # Modifies the original array


# Copy

copy_array = original_array.copy() # Creates a completely independent array

copy_array[2] = 300 # Does not affect the original array

# Display the arrays

print("Original Array:", original_array) # Output: [100, 200, 3, 4, 5]

print("Alias Array:", alias_array) # Output: [100, 200, 3, 4, 5]

print("View Array:", view_array) # Output: [100, 200, 3, 4, 5]

print("Copy Array:", copy_array) # Output: [100, 200, 300, 4, 5]

7. Write Python programs to remove duplicate values from the array [1, 3, 5, 7,
9, 9, 11, 13, 15, 17, 19, 19, 21, 23, 23]. using three different methods:

i)Basic looping

from array import *

arr = [1,3,5,7,9,9,11,13,15,17,19,19,21,23,23]

for i in range(len(arr)-1,0,-1):

for j in range(i-1, -1, -1):

if arr[i] == arr[j]:

arr.pop(j)

break

print(arr)

ii) groupby() from itertools

from itertools import groupby

data = [1,3,5,7,9,9,11,13,15,17,19,19,21,23,23]

unique_keys = []
for group in groupby(data):

unique_keys.append(group[0])

print(unique_keys)

iii) fromkeys() method

data = [1,3,5,7,9,9,11,13,15,17,19,19,21,23,23]

unique_keys = list(dict.fromkeys(data))

print(unique_keys)

8. Write a detailed note on list operations in Python, including examples

Examples:

● CREATE LIST:-

# Using square brackets

my_list = [1, 2, 3, 4, 5]
# Using list() constructor

another_list = list([6, 7, 8, 9, 10])

● ACCESS AN ELEMENT:-

my_list = [10, 20, 30, 40, 50]

# Accessing elements by index

print(my_list[0]) # Output: 10

print(my_list[2]) # Output: 30

● SLICING LISTS:-

my_list = [1, 2, 3, 4, 5, 6, 7, 8]

# Slice from index 2 to 5

print(my_list[2:6]) # Output: [3, 4, 5, 6]

# Slice with a step size of 2

print(my_list[::2]) # Output: [1, 3, 5, 7]

● MODIFYING LIST:-

my_list = [10, 20, 30, 40]

# Changing an element at a specific index

my_list[2] = 100

print(my_list) # Output: [10, 20, 100, 40]

● ADDING ELEMENTS:-

my_list = [1, 2, 3]

# Using append() to add an element

my_list.append(4)

print(my_list) # Output: [1, 2, 3, 4]

# Using insert() to add an element at index 1

my_list.insert(1, 10)
print(my_list) # Output: [1, 10, 2, 3, 4]

# Using extend() to add multiple elements

my_list.extend([5, 6, 7])

print(my_list) # Output: [1, 10, 2, 3, 4, 5, 6, 7]

● REMOVING ELEMENTS:-

my_list = [1, 2, 3, 4, 5]

# Using remove() to remove a specific element

my_list.remove(3)

print(my_list) # Output: [1, 2, 4, 5]

# Using pop() to remove an element at a specific index

my_list.pop(1)

print(my_list) # Output: [1, 4, 5]

# Using clear() to remove all elements

my_list.clear()

print(my_list) # Output: []

● LIST LENGTH, MIN,MAX,SUM

my_list = [10, 20, 30, 40, 50]

# Length of the list

print(len(my_list)) # Output: 5

# Minimum element

print(min(my_list)) # Output: 10

# Maximum element

print(max(my_list)) # Output: 50

# Sum of elements

print(sum(my_list)) # Output: 150


● SORTING LIST

my_list = [50, 10, 30, 20, 40]

# Using sort() to sort the list in place

my_list.sort()

print(my_list) # Output: [10, 20, 30, 40, 50]

# Sorting in descending order

my_list.sort(reverse=True)

print(my_list) # Output: [50, 40, 30, 20, 10]

# Using sorted() to return a new sorted list

new_list = sorted(my_list)

print(new_list) # Output: [10, 20, 30, 40, 50]

● REVERSING A LIST:-

my_list = [1, 2, 3, 4, 5]

# Reversing the list in place

my_list.reverse()

print(my_list) # Output: [5, 4, 3, 2, 1]

# Reversing using slicing

reversed_list = my_list[::-1]

print(reversed_list) # Output: [1, 2, 3, 4, 5]

● CHECKING MEMBERSHIP:-

my_list = [1, 2, 3, 4, 5]

# Checking if an element is in the list

print(3 in my_list) # Output: True

# Checking if an element is not in the list

print(5 not in my_list) # Output: False


● NESTED LISTS:-

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Accessing an element in the nested list

print(nested_list[1][2]) # Output: 6

9. Construct a Python Program to check if a given key exists in a Dictionary or


not.

d = {"BAS":"Aerospace","BCE": "Computer Science","BAI": "AIML",


"BHI":"Health Informatics"}

key = input("Enter the key to search: ")

for i in d:

if i == key:

print("Key exists")

break

else:

print("Key does not exist")

10. Implement a python program by considering the following data

nums = [0, 0, 2, 8, 1, 2, 2, 3, 3, 4,8,9] so that the result can be printed as

nums = [0, 2, 8, 1, 3, 4, 9]

nums = [0, 0, 2, 8, 1, 2, 2, 3, 3, 4,8,9]

nums1 = []

for i in range(len(nums)):

if nums[i] not in nums1:

nums1.append(nums[i])

print("New num: ",nums1) # Output: New num: [0,2,8,1,3,4,9]


11. Implement a python program by considering the following data my_list =
[9,8,7,6,5,4,3,2,1] so that the result can be printed as my_list = [1,2,3,4,5,6,7,8,9]

num = [9,8,7,6,5,4,3,2,1]

k = len(num)

for j in range(k):

for i in range(0,k-j-1):

if num[i] > num[i+1]:

num[i],num[i+1] = num[i+1], num[i]

print(num)

12. Illustrate the type codes for defining arrays with an example python
program.

While using the array module, each array has a type code that specifies the type
of elements it can store. These type codes are single characters that represent
various data types (such as integers, floating-point numbers, etc.). The type code
is specified when creating an array.

Common Type Codes for Arrays in Python

● 'b': signed char (1 byte)


● 'B': unsigned char (1 byte)
● 'u': Unicode character (deprecated in Python 3)
● 'h': signed short (2 bytes)
● 'H': unsigned short (2 bytes)
● 'i': signed int (4 bytes)
● 'I': unsigned int (4 bytes)
● 'l': signed long (4 bytes)
● 'L': unsigned long (4 bytes)
● 'f': float (4 bytes)
● 'd': double (8 bytes)

import array

# Signed char ('b' - 1 byte)

signed_char_array = array.array('b', [1, -2, 3, -4, 5])


print("Signed char array ('b'):", signed_char_array)

# Unsigned char ('B' - 1 byte)

unsigned_char_array = array.array('B', [1, 2, 3, 4, 5])

print("\nUnsigned char array ('B'):", unsigned_char_array)

# Signed short ('h' - 2 bytes)

signed_short_array = array.array('h', [100, -200, 300, -400, 500])

print("\nSigned short array ('h'):", signed_short_array)

# Unsigned short ('H' - 2 bytes)

unsigned_short_array = array.array('H', [1000, 2000, 3000, 4000, 5000])

print("\nUnsigned short array ('H'):", unsigned_short_array)

# Signed int ('i' - 4 bytes)

signed_int_array = array.array('i', [10000, -20000, 30000, -40000,


50000])

print("\nSigned int array ('i'):", signed_int_array)

# Unsigned int ('I' - 4 bytes)

unsigned_int_array = array.array('I', [100000, 200000, 300000, 400000,


500000])

print("\nUnsigned int array ('I'):", unsigned_int_array)

# Signed long ('l' - 4 bytes)

signed_long_array = array.array('l', [1000000, -2000000, 3000000,


-4000000, 5000000])

print("\nSigned long array ('l'):", signed_long_array)

# Unsigned long ('L' - 4 bytes)

unsigned_long_array = array.array('L', [10000000, 20000000, 30000000,


40000000, 50000000])

print("\nUnsigned long array ('L'):", unsigned_long_array)

# Float ('f' - 4 bytes)


float_array = array.array('f', [1.1, -2.2, 3.3, -4.4, 5.5])

print("\nFloat array ('f'):", float_array)

# Double ('d' - 8 bytes)

double_array = array.array('d', [1.23456789, -2.3456789, 3.456789,


-4.567890, 5.678901])

print("\nDouble array ('d'):", double_array)

13. Write a program to count the number of times the letters ‘b’, ‘a’, and ‘n’
appear in the string 'banana', without using the count() function

str = "banana"

str_alphabet = []

count_b = 0

count_a = 0

count_n = 0

for i in range(len(str)):

str_alphabet.append(str[i])

for j in str_alphabet:

if j == 'b':

count_b +=1

elif j == 'a':

count_a +=1

else:

count_n +=1

print("The number of 'b' in BANANA =", count_b)

print("The number of 'a' in BANANA =", count_a)

print("The number of 'n' in BANANA =", count_n)


14. Write a Python program to remove duplicates from an ordered array. Your
program should maintain the original order of the array and should not use
built-in functions like set (). Sample Input: [1, 2, 2, 3, 4, 4, 5], Sample Output: [1,
2, 3, 4, 5]

import array

arr = [1,2,2,3,4,4,5]

for i in range(len(arr)-1,0,-1):

for j in range(i-1, -1, -1):

if arr[i] == arr[j]:

arr.pop(j)

break

print(arr)

15. Write a Python program to find the 3rd smallest number in the unsorted
array [7, 10, 4, 3, 20, 15].

import array

arr = [7,10,4,3,20,15]

for i in range(len(arr)):

for j in range(0,len(arr)-i-1):

if arr[j] > arr[j+1]:

arr[j],arr[j+1] = arr[j+1], arr[j]

print("The 3rd smallest number: ",arr[2])

16. Explain list operations in Python (adding, removing, and accessing


elements). Provide examples of list slicing and list comprehension.

SAME ANSWER AS QUESTION 8 (JUST A SEGMENT OF ANSWER 8)

17. Write a Python program to implement the stack and queue using list
operations.
● Stack Implementation using List

A stack is a collection of elements that follows the Last In, First Out (LIFO)
principle. Python’s list provides methods like append() to add an element to the
end and pop() to remove the element from the end, which makes it easy to
implement a stack.

Stack Operations:

● push(): Add an element to the top of the stack.


● pop(): Remove the element from the top of the stack.
● peek(): View the top element without removing it.
● is_empty(): Check if the stack is empty.
● size(): Get the size of the stack

Example:

class Stack:

def __init__(self):

self.stack = []

def push(self, item):

self.stack.append(item) # Add element to the top of the stack

def pop(self):

if self.is_empty():

return "Stack is empty"

return self.stack.pop() # Remove the element from the top

def peek(self):

if self.is_empty():

return "Stack is empty"

return self.stack[-1] # Return the top element without removing it

def is_empty(self):

return len(self.stack) == 0 # Return True if stack is empty


def size(self):

return len(self.stack) # Return the size of the stack

# Example usage of Stack

stack = Stack()

stack.push(10)

stack.push(20)

stack.push(30)

print("Top element:", stack.peek()) # Output: 30

print("Size of stack:", stack.size()) # Output: 3

print("Pop element:", stack.pop()) # Output: 30

print("Size of stack after pop:", stack.size()) # Output: 2

● Queue Implementation using List

A queue is a collection of elements that follows the First In, First Out (FIFO)
principle. In Python, lists provide the append() method to add elements at the end
and pop(0) to remove the element from the front, making it easy to implement a
queue. However, using pop(0) can be inefficient for large queues due to its O(n)
complexity.

Queue Operations:

● enqueue(): Add an element to the end of the queue.


● dequeue(): Remove the element from the front of the queue.
● front(): View the front element without removing it.
● is_empty(): Check if the queue is empty.
● size(): Get the size of the queue.

Example:

class Queue:

def __init__(self):

self.queue = []
def enqueue(self, item):

self.queue.append(item) # Add element to the end of the queue

def dequeue(self):

if self.is_empty():

return "Queue is empty"

return self.queue.pop(0) # Remove the element from the front

def front(self):

if self.is_empty():

return "Queue is empty"

return self.queue[0] # Return the front element without removing it

def is_empty(self):

return len(self.queue) == 0 # Return True if queue is empty

def size(self):

return len(self.queue) # Return the size of the queue

# Example usage of Queue

queue = Queue()

queue.enqueue(10)

queue.enqueue(20)

queue.enqueue(30)

print("Front element:", queue.front()) # Output: 10

print("Size of queue:", queue.size()) # Output: 3

print("Dequeue element:", queue.dequeue()) # Output: 10

print("Size of queue after dequeue:", queue.size()) # Output: 2

18. Write a Python program to reverse the elements of an array without using
any in-built functions.
def reverse_array(arr):

start = 0

end = len(arr) - 1

while start < end:

arr[start], arr[end] = arr[end], arr[start]

start += 1

end -= 1

arr = [1, 2, 3, 4, 5, 6]

print("Original array:", arr)

reverse_array(arr)

print("Reversed array:", arr)

19. Write a Python program to convert a multidimensional array to a list

def flatten_array(arr):

flat_list = []

for sublist in arr:

flat_list.extend(sublist)

return flat_list

multi_dimensional_array = [[1, 2, 3], [4, 5], [6, 7, 8]]

print("Original Multidimensional Array:", multi_dimensional_array)

flat_list = flatten_array(multi_dimensional_array)

print("Flattened List:", flat_list) # Output: [1,2,3,4,5,6,7,8]

20. You are managing a library system with two sections: Fiction and
Nonfiction. The registered members in these sections are as follows: Members in
Fiction Section: [‘Ajay’, ‘Babu’, ‘Charlie’, ‘David’, ‘Elizabeth’] Members in
Non-Fiction Section: [‘Charlie’, ‘David’, ‘Frank’, ‘Grace’, ‘Babu’] Using Python
sets, answer the following questions: Identify the members who registered in
both sections. List the members who registered in only one section (not both).
Determine if all members of the Fiction section also registered in the Non
Fiction section. Find the total number of unique members across both sections.

fiction = {'Ajay', 'Babu','Charlie', 'David', 'Elizabeth'}

non_fiction = {'Charlie', 'David', 'Frank', 'Grace', 'Elizabeth'}

#Identify the members who registered in both sections.

common = fiction.intersection(non_fiction)

print("Common members between fiction and non_fiction: ", common)

#List the members who registered in only one section (not both).

separate = fiction.symmetric_difference(non_fiction)

print("Members in only one section: ", separate)

#Determine if all members of the Fiction section also registered in the


Non Fiction section.

subset = fiction.issubset(non_fiction)

print("Are all members in fiction also a part of nonfiction?: ",


subset)

#Find the total number of unique members across both sections.

total = fiction.union(non_fiction)

print("Total number of unique members: ", len(total))

21. A university manages its student database using a dictionary. Each student
has a unique Student ID as the key, and their details (such as name, age,
courses enrolled, and GPA) are stored as a nested dictionary. You are required
to implement the following operations using dictionary methods: 1. Add or
Update a Student’s Information: If the student already exists, use setdefault()
to ensure that the courses and GPA have default values. 2. Check Student’s
Enrolment in a specific course using their Student ID. 3. List All Students with
their details (Student ID, Name, Age, Courses, GPA). 4. Retrieve a Student’s GPA
using their Student ID. 5. Update a Student’s Course List by adding or removing
a course. 6. Remove a Student from the database using their Student ID and
finally clear the Entire Student Database

student_db = {}

# 1. Add or Update a Student's Information

def add_or_update_student(student_id, name, age, courses=None,


gpa=None):

student_db.setdefault(student_id, {"name": name, "age": age,


"courses": courses or [], "gpa": gpa or 0.0})

print(f"Student {student_id} has been added/updated.")

# 2. Check Student’s Enrollment in a Specific Course

def is_enrolled_in_course(student_id, course):

if student_id in student_db:

return course in student_db[student_id]["courses"]

else:

print(f"Student {student_id} not found.")

return False

# 3. List All Students with Their Details

def list_all_students():

if not student_db:

print("No students in the database.")

else:

for student_id, details in student_db.items():

print(f"Student ID: {student_id}, Details: {details}")

# 4. Retrieve a Student’s GPA

def get_gpa(student_id):

if student_id in student_db:
return student_db[student_id]["gpa"]

else:

print(f"Student {student_id} not found.")

return None

# 5. Update a Student’s Course List by Adding or Removing a Course

def update_course_list(student_id, course, add=True):

if student_id in student_db:

if add:

student_db[student_id]["courses"].append(course)

print(f"Course '{course}' added for Student {student_id}.")

else:

try:

student_db[student_id]["courses"].remove(course)

print(f"Course '{course}' removed for Student


{student_id}.")

except ValueError:

print(f"Course '{course}' not found for Student


{student_id}.")

else:

print(f"Student {student_id} not found.")

# 6. Remove a Student from the Database

def remove_student(student_id):

if student_id in student_db:

student_db.pop(student_id)

print(f"Student {student_id} removed from the database.")

else:
print(f"Student {student_id} not found.")

def clear_database():

student_db.clear()

print("The student database has been cleared.")

22. Write the algorithm and python implementation for the following Find the
kth maximum element of an array (4M) Find the kth minimum element of an
array (4M)

print("CREATING AN ARRAY")

arr = []

num = int(input("How many numbers in array: "))

for i in range(0,num):

a = int(input("Enter a number: "))

arr.append(a)

print("The array formed is: ",arr)

print(" ")

k = int(input("Which kth number minimum and maximum number do you need:


"))

arr.sort()

print("The",k,"th minimum number in array is: ",arr[k-1])

print("The",k,"th maximum number in array is: ",arr[-k])

Algorithm according to code.

23. Write a python implementation to find the Kth minimum element in an


array. (4 M) Write a python program to insert a newly created item ‘24’ before
the second element in an existing array. (2M) Write a python program to
remove the first occurrence of a 10 element from an array = [4,9,10,9,3,8,5,10].
(2M) Write a python program to print the 2 smallest and largest numbers in the
given array that contains the following items [95, 25, 75, 35, 65, 45, 85, 55]. (4M)
# Write a python implementation to find the Kth minimum element in an
array. (4 M)

print("CREATING AN ARRAY")

arr = []

num = int(input("How many numbers in array: "))

for i in range(0,num):

a = int(input("Enter a number: "))

arr.append(a)

print("The array formed is: ",arr)

print(" ")

def kth_minimum_element():

k = int(input("Which kth number minimum do you need: "))

arr.sort()

print("The",k,"th minimum number in array is: ",arr[k-1])

kth_minimum_element()

#Write a python program to insert a newly created item ‘24’ before the
second element in an existing array. (2M)

def insert_an_item():

n =int(input("Enter the number to insert: "))

i = int(input("Enter the index number to insert: "))

arr.insert(i,n)

print("The new array: ",arr)

insert_an_item()

# Write a python program to remove the first occurrence of a 10 element


from an array = [4,9,10,9,3,8,5,10]. (2M)

def remove_the_first_10():
array = [4,9,10,9,3,8,5,10]

for i in range(len(array)):

if array[i]==10:

array.remove(10)

break

print("The new array: ",array)

remove_the_first_10()

#Write a python program to print the 2 smallest and largest numbers in


the given array that contains the following items [95, 25, 75, 35, 65,
45, 85, 55]. (4M)

def two_smallest_and_largest_numbers():

arr = [95,25,75,35,65,45,85,55]

new_arr = []

k = len(arr)

for j in range(k):

for i in range(0,k-j-1):

if arr[i] > arr[i+1]:

arr[i],arr[i+1] = arr[i+1], arr[i]

# To print the 2 smallest and largest numbers:

new_arr.append(arr[0])

new_arr.append(arr[1])

new_arr.append(arr[-1])

new_arr.append(arr[-2])

print("The new array: ", new_arr)

two_smallest_and_largest_numbers()
24. A nested dictionary represents a stock maintenance of a mobile shop with
mobile name as keys and their details (like model, cost and product ID) as
another dictionary. Write a python program to: Add a new mobile to the
dictionary. Update the cost of an existing mobile. Display all mobile name and
their details.

# Initialize the nested dictionary for stock maintenance

mobile_shop = {}

# 1. Add a new mobile to the dictionary

def add_mobile(name, model, cost, product_id):

if name in mobile_shop:

print(f"Mobile {name} already exists.")

else:

mobile_shop[name] = {"model": model, "cost": cost,


"product_id": product_id}

print(f"Mobile {name} added successfully.")

# 2. Update the cost of an existing mobile

def update_cost(name, new_cost):

if name in mobile_shop:

mobile_shop[name]["cost"] = new_cost

print(f"The cost of {name} has been updated to {new_cost}.")

else:

print(f"Mobile {name} not found.")

# 3. Display all mobile names and their details

def display_all_mobiles():

if not mobile_shop:

print("No mobiles available in the shop.")

else:
print("Mobile Stock Details:")

for name, details in mobile_shop.items():

print(f"Mobile Name: {name}, Details: {details}")

# Example Usage

# Adding new mobiles

add_mobile("iPhone", "iPhone 13", 80000, "A123")

add_mobile("Samsung", "Galaxy S21", 60000, "B456")

# Updating the cost of an existing mobile

update_cost("iPhone", 85000)

# Displaying all mobiles

display_all_mobiles()

25. A district sports academy is organizing a sports event on Independence


Day, and two events are being conducted at the same time: Long Jump and
Javelin. The organizing committee has to shortlist the participants in order to
avoid confusion. The participants are as follows: Participants enrolled in Long
Jump: ['Ajay', 'John', 'Nikel', 'Marlin', 'Ravi', 'Sanjay', 'Rithvik'] Participants
enrolled in Javelin: ['Ravi', 'Olivia', 'Nithin', 'James', 'Edwin', 'John', 'Akshay']
Using Python sets, write python code to solve these problems. List the
participants who enrolled for only one event (not both). Find the number of
unique participants across both events. Determine if all participants of long
jump also enrolled for Javelin. Identify participants who enrolled for both
event

SAME AS ANSWER 20

26. Write a Python program to remove duplicates from a list

SAME AS ANSWER 14

27. Answer the following questions with justification:

Is it possible to add a list as an element in a set? Is it possible to add a tuple


as an element in a set?
● No, we cannot add a list as an element in a set. Sets are mutable and only
immutable elements can be added in it. However, Lists are mutable (their
contents can be changed after creation)
○ Example:

my_set = {1, 2, 3}

my_list = [4, 5]

# This will raise a TypeError because lists are mutable.

my_set.add(my_list)

● Yes, we can add a tuple as an element in a set. Since tuples are immutable
(their content cannot be changed after creation), they apply to the
conditions for being added to the set.
○ Example:

my_set = {1, 2, 3}

my_tuple = (4, 5)

my_set.add(my_tuple)

print(my_set) # {1, 2, 3, (4, 5)}

Is it possible to add a dictionary as an element in a set?

No, you cannot add a dictionary as an element of a set.

In Python, dictionaries are mutable objects, which means their contents can
change. Since sets require their elements to be hashable (i.e., their hash value
must be constant and unchanging), dictionaries, being mutable, are not hashable.
As a result, you cannot add a dictionary as an element of a set.

28. Write the output of the following Python Program: university=('V', 'I','T','B',
'h','o','p', 'a','l') #Tuple

print(university) : ('V', 'I','T','B', 'h','o','p', 'a','l')


print(university[1]) : I

print(university[-4]) : o

print(university[-2]) : a

print(university[-2:-6:1]) : ()

print(university[-2:-6:-1]) : (‘a’, ‘p’, ‘o’, ‘h’)

print(university[-10:-7:-1]) : ()

print(university[-10:-6:1]) : (‘V’, ‘I’, ‘T’)

print(university[-10:-6]) : (‘V’, ‘I’, ‘T’)

print(university[0:3]) : (‘V’, ‘I’, ‘T’)

29. Write a Python program to demonstrate tuple operations.

1. Create a tuple with five different numbers.

2. Print the tuple.

3. Access and print the first and last element of the tuple.

4. Change one of the numbers in the tuple (if tuples are immutable, how can
you still change it?) — show how to create a new tuple that reflects this change
without modifying the original tuple.

5. Print the length of the tuple

#1. Create a tuple with five different numbers.

tup_list = []

a = int(input("How many number in tuple: "))

for i in range(0,a):

b = int(input("Enter number: "))

tup_list.append(b)

#2. Print the tuple.

tup = tuple(tup_list)

print("The tuple created is: ", tup)


#3. Access and print the first and last element of the tuple.

print("The first element of tuple is: ",tup[0])

print("The last element of tuple is: ",tup[-1])

#4. Change one of the numbers in the tuple

n= int(input("Enter the number to change: "))

k = int(input("Enter the updated value: "))

for i in range(len(tup_list)):

if tup_list[i] == n:

tup_list.remove(n)

tup_list.insert(i,k)

tup_list1 = tup_list

updated_tup = tuple(tup_list1)

print("The updated tuple is: ", updated_tup)

#5. Print the length of the tuple

print("The length of the tuple is: ", len(tup))

30. Write a Python program to reverse the order of elements in a given list. Use
slicing to reverse the list efficiently.

def reverse_list(input_list):

return input_list[::-1]

original_list = [1, 2, 3, 4, 5]

reversed_list = reverse_list(original_list)

print("Original List:", original_list)

print("Reversed List:", reversed_list)


31. Discuss the differences between Python lists and tuples in terms of:

1. Mutability. 2. Use cases. 3. Memory efficiency. Provide examples where tuples


are preferred over lists

● Mutability
○ Lists are mutable: You can change the content (add, remove, modify
elements) after the list is created.
○ Tuples are immutable: Once a tuple is created, its elements cannot be
changed.
● Use cases
○ Lists are used when the values have to be updated after short
durations. Example- managing a collection of items
○ Tuples are used when the values have to be fixed after they are
stored and no changes should be done on it further. Example- setting
coordinates of a place.
● Memory efficiency
○ Lists are less memory-efficient because they store additional
overhead for dynamic resizing.
○ Tuples are more memory-efficient due to their immutability and fixed
size

When to Prefer Tuples Over Lists

● When Data Should Not Change: Example: Storing constants like days of the
week.

days_of_week = ("Monday", "Tuesday", "Wednesday", "Thursday",


"Friday", "Saturday", "Sunday")

print(days_of_week)

● Keys in Dictionaries: Tuples can be used as dictionary keys because they


are immutable and hashable, unlike lists.

my_dict = {("John", "Doe"): 30, ("Alice", "Smith"): 25}

print(my_dict[("John", "Doe")]) # Output: 30

● Data Integrity: Example: Passing fixed configurations or function


arguments.

def display_coordinates(coords):

print(f"x: {coords[0]}, y: {coords[1]}")

coordinates = (10, 20)


display_coordinates(coordinates)

● Improved Performance:
○ Tuples are faster to access compared to lists because of their
immutability.

32. In order to calculate the factorial of a non-negative integer without the use
of recursion or built in functions such as math.factorial(), write a Python
function. Your function should produce a solution with the ideal time complexity
and be able to handle huge input numbers with ease. Provide an example to
illustrate.

def factorial_iterative(n):

if n == 0:

return 1

result = 1

for i in range(1, n + 1):

result *= i

return result

# Example usage

number = 20 # Change this to a huge number to test performance

factorial_result = factorial_iterative(number)

print(f"The factorial of {number} is: {factorial_result}")

33. A restaurant in a small town has a customer base of 150 regular diners.
Each day, about 30 different customers dine in, and the restaurant is open 25
days a month. You have a list of lists with the names of customers who dined in
each day over the past month. Find the unique customers to include them in a
loyalty program.

# Sample data: List of lists representing customers who dined in each


day

daily_customers = [

["Alice", "Bob", "Charlie", "David"],

["Alice", "Eve", "Frank", "Grace"],


["Charlie", "Hannah", "Ian", "David"],

["Bob", "Frank", "Charlie", "Eve"],

# Add more daily lists for 25 days

# Step 1: Flatten the list of lists into a single list of all customers

all_customers = [customer for day in daily_customers for customer in


day]

# Step 2: Use a set to find unique customers

unique_customers = set(all_customers)

# Step 3: Display unique customers eligible for the loyalty program

print(f"Unique customers eligible for the loyalty program


({len(unique_customers)}):")

print(unique_customers)

34. Write a function find_index(), which returns the index of a number in the
Fibonacci sequence, if the number is an element of this sequence and returns-1
if the number is not contained in it, call this function using user input and
display the result

def find_index(num):

a, b = 0, 1

index = 0

if num == 0:

return 0

elif num == 1:

return 1

while b < num:

a, b = b, a + b

index += 1
if b == num:

return index + 1

return -1

if __name__ == "__main__":

try:

number = int(input("Enter a number to find its index in the


Fibonacci sequence: "))

result = find_index(number)

if result == -1:

print(f"{number} is not a Fibonacci number.")

else:

print(f"The index of {number} in the Fibonacci sequence is:


{result}")

except ValueError:

print("Please enter a valid integer.")

35. Write down the output of the following program.


num=(10,20,30,40,50,60,70,80,90,100)

print(num) : (10,20,30,40,50,60,70,80,90,100)

print(num[1]) : 20

print(num[:0]) : ()

print(num[-4]) : 70

print(num[::4]) : (10,50,90)

print(num[-3:-8:1]) : ()

print(num[-3:-8:-1]) : (80,70,60,50,40)

print(num[-10:-6:-1]) : ()

print(num[-10:-6:1]) : (10,20,30,40)
print(num[-10:-6]) : (10,20,30,40)

print(num[0:]) : (10,20,30,40,50,60,70,80,90,100)

36. Write a Python program that takes two lists and prints all the common
elements of those two lists.

print("CREATING LIST 1")

l1= []

num1 = int(input("How many number in list 1: "))

for i in range(0,num1):

a = int(input("Enter a number: "))

l1.append(a)

print("List 1: ", l1)

print("CREATING LIST 2")

l2 = []

num2 = int(input("How many number in list2: "))

for j in range(0,num2):

b = int(input("Enter a number: "))

l2.append(b)

print("List 2: ", l2)

dictionary_1 = {element: index for index, element in enumerate(l1)}

dictionary_2 = {element: index for index, element in enumerate(l2)}

common_keys = set(dictionary_1.keys()) & set(dictionary_2.keys())

print("The common numbers in List 1 and List 2: ", list(common_keys))

37. What is the difference between list, set, tuple and dictionary in python?

1. List
● Definition: A list is an ordered, mutable (changeable) collection of elements
that can hold multiple items of any data type.
● Syntax: my_list = [1, 2, 3, 4, 5]
● Characteristics:
○ Ordered: The elements in a list have a defined order, and the order is
maintained.
○ Mutable: You can change elements, add or remove items after the list
is created.
○ Allows Duplicates: Lists can contain duplicate elements.
○ Indexed: Access elements via indices.
● Use Cases:
○ Storing a sequence of elements that might need to be modified.
○ Example: Storing shopping lists, student names, etc.
● Example:
my_list = [10, 20, 30, 40, 50]

my_list[1] = 25 # Modify an element

print(my_list) # Output: [10, 25, 30, 40, 50]

2. Set

● Definition: A set is an unordered collection of unique elements. It does not


allow duplicates and provides fast membership testing.
● Syntax: my_set = {1, 2, 3, 4, 5}
● Characteristics:
○ Unordered: The elements in a set are not stored in any particular
order, and the order may vary.
○ Mutable: You can add or remove elements, but the elements
themselves must be immutable (e.g., numbers, strings, tuples).
○ No Duplicates: A set cannot contain duplicate values.
○ No Indexing: You cannot access elements by index.
● Use Cases:
○ Storing a collection of unique items, like the set of participants in a
survey.
○ Example: Set operations like union, intersection, and difference.
● Example:
my_set = {1, 2, 3, 4, 5}

my_set.add(6) # Adding an element

my_set.remove(4) # Removing an element


print(my_set) # Output: {1, 2, 3, 5, 6}

3. Tuple

● Definition: A tuple is an ordered, immutable collection of elements.


● Syntax: my_tuple = (1, 2, 3, 4, 5)
● Characteristics:
○ Ordered: The elements have a defined order, and the order is
preserved.
○ Immutable: Once created, the elements of a tuple cannot be
changed.
○ Allows Duplicates: A tuple can contain duplicate elements.
○ Indexed: You can access elements via indices.
● Use Cases:
○ Used to represent fixed collections of data that should not change,
such as coordinates, function arguments, and return values.
○ Example: Representing a point in 2D/3D space.
● Example:
my_tuple = (10, 20, 30)

print(my_tuple[1]) # Output: 20

4. Dictionary

● Definition: A dictionary is an unordered collection of key-value pairs, where


each key is unique.
● Syntax: my_dict = {"name": "Alice", "age": 25, "city": "New
York"}
● Characteristics:
○ Unordered: The elements in a dictionary are not stored in a specific
order (although Python 3.7+ maintains insertion order).
○ Mutable: You can change, add, or remove key-value pairs.
○ Keys are Unique: A dictionary cannot have duplicate keys, but values
can be duplicated.
○ Indexed by Keys: You access values by their keys.
● Use Cases:
○ Storing data that is paired in key-value format, such as user profiles,
configurations, etc.
○ Example: Using a dictionary to store a contact list where names are
keys and phone numbers are values.
● Example:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}

my_dict["age"] = 26 # Modify a value

print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city':


'New York'}

38. Explain the below given terms with respect to 1-D array in python: 1.
Comparison operations 2. any () 3. all () 4.where ()

● Comparison Operations on 1-D Array

In Python, comparison operations can be performed element-wise on 1-D arrays,


often using NumPy (which provides efficient array handling). These operations
compare each element of the array against a value or another array and return a
new array of Boolean values (True or False) indicating whether the comparison is
true for each element.

Common comparison operations:

● ==: Element-wise equality comparison


● !=: Element-wise inequality comparison
● <, <=, >, >=: Element-wise comparison for less than, less than or equal to,
greater than, greater than or equal to

Example:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

result = arr > 30

print(result) # Output: [False False False True True]

● any() Function on 1-D Array

The any() function checks whether any element of a 1-D array evaluates to True.
It returns a Boolean value: True if at least one element is True, and False if all
elements are False.

Syntax: numpy.any(array)
Example:

import numpy as np

arr = np.array([0, 2, 0, 0])

result = np.any(arr)

print(result) # Output: True

● all() Function on 1-D Array

The all() function checks whether all elements in the array evaluate to True. It
returns True if all elements are True, and False if at least one element is False.

Syntax: numpy.all(array)

Example:

import numpy as np

arr = np.array([1, 2, 3, 4])

result = np.all(arr > 0)

print(result) # Output: True

● where() Function on 1-D Array

The where() function is used to select elements from an array based on a


condition. It returns the indices of the elements that satisfy the condition or allows
you to perform conditional replacement of values in the array.

Syntax: numpy.where(condition, [x, y])

● condition: A Boolean condition to be evaluated.


● x: The value to be returned for elements that meet the condition.
● y: The value to be returned for elements that do not meet the condition.

Example:
import numpy as np

arr = np.array([10, 20, 30, 40, 50])

indices = np.where(arr > 30)

print(indices) # Output: (array([3, 4]),)

39. Explain the different way to declare the list data structure in python. Also
explain the following list methods with an example. a) append () b) pop () c)
index() d) extend ()

In Python, a list is a collection of items that is ordered, mutable, and allows


duplicate elements. Here are various ways to declare a list:

1) Using Square Brackets ([]): my_list = [1, 2, 3, 4, 5]


2) Using the list() Constructor: my_list = list((1, 2, 3, 4, 5))
3) Empty List: empty_list = []
4) List with Mixed Data Types: mixed_list = [1, "hello", 3.14, True]

List Methods with Examples

a) append()

● Description: Adds a single element to the end of the list.


● Example:
my_list = [1, 2, 3]

my_list.append(4)

print(my_list) # Output: [1, 2, 3, 4]

b) pop()

● Description: Removes and returns the last element of the list by default. You
can also specify the index to remove an element from that position.
● Example:
my_list = [1, 2, 3, 4]

last_element = my_list.pop() # Removes and returns 4


print(my_list) # Output: [1, 2, 3]

c) index()

● Description: Returns the index of the first occurrence of the specified


element in the list. Raises a ValueError if the element is not found.
● Example:
my_list = [1, 2, 3, 2, 4]

index = my_list.index(2) # Finds the first occurrence of 2

print(index) # Output: 1

d) extend()

● Description: Adds all elements from another iterable (like a list, tuple, or
string) to the end of the current list.
● Example:
my_list = [1, 2, 3]

my_list.extend([4, 5, 6])

print(my_list) # Output: [1, 2, 3, 4, 5, 6]

40. Implement the queue data structure with insert and delete operations using
tuple in python

Tuples are immutable, so we cannot modify them directly. However, we can


simulate a queue by converting the tuple to a list for insertion or deletion and then
back to a tuple.

def enqueue(queue, element):

"""Insert an element into the queue."""

temp_list = list(queue)

temp_list.append(element)

return tuple(temp_list)

def dequeue(queue):
"""Remove and return the first element of the queue."""

if len(queue) == 0:

return None, queue

temp_list = list(queue)

first_element = temp_list.pop(0)

return first_element, tuple(temp_list)

# Example usage

queue = () # Start with an empty queue (tuple)

# Insert elements

queue = enqueue(queue, 10)

queue = enqueue(queue, 20)

queue = enqueue(queue, 30)

print("Queue after enqueue operations:", queue) # Output: (10, 20, 30)

# Delete elements

element, queue = dequeue(queue)

print("Dequeued element:", element) # Output: 10

print("Queue after dequeue operation:", queue) # Output: (20, 30)

You might also like