Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

keyboard_arrow_down Python Mid Term Exam Answersheet

** Name - Gaurav Shankar Kumar **

Question 1: Write a Python function that takes a list of integers as input and returns the sum of all even numbers in the list.

def sum_even_numbers(numbers):

even_sum = 0

for num in numbers:


if num % 2 == 0:
even_sum += num
return even_sum

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = sum_even_numbers(numbers)
print("Sum of even numbers:", result)

Sum of even numbers: 20

Question 2: Implement a Python class called BankAccount with the following attributes and methods:

Attributes: account_number (string), balance (float)


Methods: init(self, account_number, initial_balance), deposit(self, amount), withdraw(self, amount), get_balance(self)

class BankAccount:

def __init__(self, account_number, initial_balance=0.0):


self.account_number = account_number
self.balance = initial_balance

def deposit(self, amount):


if amount > 0:
self.balance += amount

def withdraw(self, amount):

if 0 < amount <= self.balance:


self.balance -= amount
else:
print("Insufficient funds for withdrawal.")

def get_balance(self):

return self.balance

#testing

account = BankAccount("123456789", 1000.0)


account.deposit(500.0)
account.withdraw(200.0)

current_balance = account.get_balance()
print("Current balance:", current_balance)

Current balance: 1300.0

Question 3: Given a string, write a Python function to reverse the order of words in the string.

For example, if the input string is "The quick brown fox", the output should be "fox brown quick The".
def reverse_words(input_string):
words = input_string.split()
reversed_words = words[::-1]
reversed_string = ' '.join(reversed_words)
return reversed_string

# testing

input_str = "The quick brown fox"


print(reverse_words(input_str))

fox brown quick The

Question 4: Implement a Python generator function that generates the Fibonacci sequence up to a given number n.

def fibonacci_sequence(n):
a, b = 0, 1
while a <= n:
yield a
a, b = b, a + b

# testing
n = 21
fib_gen = fibonacci_sequence(n)
for fib_number in fib_gen:
print(fib_number)

0
1
1
2
3
5
8
13
21

Question 6: Implement a Python function that takes a list of dictionaries representing students and their grades, and returns the name of the
student with the highest average grade.

def student_with_highest_average(students):

highest_avg = -1
top_student = ""

for student in students:


avg_grade = sum(student["grades"]) / len(student["grades"])
if avg_grade > highest_avg:
highest_avg = avg_grade
top_student = student["name"]

return top_student

students = [
{"name": "Alice", "grades": [85, 92, 78]},
{"name": "Bob", "grades": [72, 88, 91]},
{"name": "Charlie", "grades": [67, 74, 89]},
{"name": "Gaurav", "grades": [100, 100, 100]}
]

print(student_with_highest_average(students))

Gaurav

Question 7: Write a Python function that takes a string as input and returns a dictionary where the keys are characters in the string, and the
values are the counts of how many times each character appears.
def character_count(input_string):
char_count = {}

for char in input_string:


if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count

input_str = "gaurav shankar kumar"


print(character_count(input_str))

{'g': 1, 'a': 5, 'u': 2, 'r': 3, 'v': 1, ' ': 2, 's': 1, 'h': 1, 'n': 1, 'k': 2, 'm': 1}

Question 8: List down difference between a tuple and a list.

#### List ####

# Mutable (can be changed after creation)


# Enclosed in square brackets []
# Wide range of methods for adding, removing, sorting, etc.
# Generally less memory efficient due to dynamic resizing
# Slightly slower for element access and modification due to dynamic nature
# Storing collections of data that might need to be changed

my_list = [1, 2, 3]
my_list.append(4)
my_list.remove(2)
my_list[0] = 10
print(my_list)

# Tuple

# Immutable (cannot be changed after creation)


# Enclosed in parentheses ()
# Limited operations: indexing, slicing, unpacking, concatenation
# More memory efficient as size is fixed at creation
# Slightly faster for element access due to fixed size
# Storing collections of related data that should not be changed

my_tuple = (1, 2, 3)
# my_tuple.append(4) # not allow
# my_tuple[0] = 10 # not allow
print(my_tuple)

[10, 3, 4]
(1, 2, 3)

Question 9: Implement a Python function that takes a list of integers and returns a list of all subsets of the original list.

def get_subsets(nums):
subsets = []
n = len(nums)

for i in range(2**n):
subset = []
for j in range(n):
if i & (1 << j):
subset.append(nums[j])
subsets.append(subset)
return subsets

nums = [1, 2, 3]
print(get_subsets(nums))

[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Question 10: Write a Python decorator function that caches the result of a function call based on its arguments. If the function is called with the
same arguments again, the cached result should be returned instead of recomputing the function.
def memory_decorator(func):
cache = {}

def memory_func(*args, **kwargs):


key = (args, frozenset(kwargs.items()))

if key not in cache:


cache[key] = func(*args, **kwargs)
return cache[key]

return memory_func

@memory_decorator
def expensive_function(num):
print("Computing...", num)
return num * 2

result1 = expensive_function(5)
result2 = expensive_function(5)
result3 = expensive_function(4)
result4 = expensive_function(6)

print(result1, result2, result3, result4)

Computing... 5
Computing... 4
Computing... 6
10 10 8 12

You might also like