Page 447 - Computer Science V2.0 Class 11
P. 447
# Example usage:
myList = [4, 7, 2, 9, 5, 1]
print('List content', myList)
result = findLargestElement(myList)
print(f"The largest element in the list is: {result}")
4. Write a function to return the second largest number from a list of numbers.
Ans. def findSecondLargestElement(myList):
if len(myList) < 2:
return None # Return None if the list has fewer than two elements
largestElement = secondLargestElement = float('-inf')
for element in myList:
if element > largestElement:
secondLargestElement = largestElement
largestElement = element
elif element > secondLargestElement and element != largestElement:
secondLargestElement = element
return secondLargestElement
# Example usage:
myList = [4, 7, 2, 9, 5, 1]
print('List content', myList)
result = findSecondLargestElement(myList)
if result is not None:
print(f"The second largest element in the list is: {result}")
else:
print("List has fewer than two elements.")
5. Write a program to read a list of n integers and find their median.
Note: The median value of a list of values is the middle one when they are arranged in order. If there are two middle values then take
their average.
Hint: You can use an built-in function to sort the list
Ans. def calculateMedian(inputList):
sortedList = sorted(inputList)
n = len(sortedList)
if n % 2 == 0:
mid1 = sortedList[n // 2 - 1]
mid2 = sortedList[n // 2]
median = (mid1 + mid2) / 2
else:
median = sortedList[n // 2]
return median
n = int(input("Enter the number of integers: "))
Dictionaries 433

