Page 452 - Computer Science Class 11 With Functions
P. 452
for i in range(0, numElements): #list input element-wise
num = int(input())
numList.append(num)
print("Contents of list:", numList)
averageResult = calculateAverage(numList)
if averageResult is not None:
print(f"The average of the numbers is: {averageResult}")
else:
print("The list is empty.")
Program 41
Write a function that takes a list as an input and returns the middle element of the list. If the list has even number
of elements, then it returns average of both elements.
Ans. def findMiddleElement(inputList):
'''
Objective : To find middle element of the list
Input Parameter : inputList - list
Return Value : numeric value
'''
length = len(inputList)
if length == 0:
return None # Return None for an empty list
elif length % 2 == 1: # Odd number of elements
middleIndex = length // 2
return inputList[middleIndex]
else: # Even number of elements
middleIndex1 = length // 2 - 1
middleIndex2 = length // 2
middleElement1 = inputList[middleIndex1]
middleElement2 = inputList[middleIndex2]
return (middleElement1 + middleElement2) / 2
# Example usage:
myListOdd = [1, 2, 3, 4, 5]
middleResultOdd = findMiddleElement(myListOdd)
myListEven = [1, 2, 3, 4]
middleResultEven = findMiddleElement(myListEven)
if middleResultOdd is not None:
print(f"Middle element (odd): {middleResultOdd}")
if middleResultEven is not None:
print(f"Middle element (even): {middleResultEven}")
450 Touchpad Computer Science-XI

