Project Level 1: Beginner
This project is designed for beginner learners who are still learning and practicing Python fundamentals.
Project Description
We will start this week with a small project about tuples. Your task is to write a program that takes a tuple of numbers, finds the second largest number, and prints out that number.
You can start your program by having this tuple as the first line:
numbers = (10, 5, 8, 20, 15)
👉 Note the difference between tuples and lists? Tuples are surrounded by round parenthesis, and they are immutable. Otherwise, they behave very similar.
Expected Output
Here is what your program should print out:
Learning Benefits
Tuple Iteration: Practice looping through a tuple efficiently.
Use of functions: Practice the use of the proper function to find the second large number of a sequence.
Prerequisites
Required Libraries: No libraries are needed for this project.
Required Files: No files are needed for this project.
IDE: You can use any IDE on your computer to code the project.
Danger Zone
We provide two solutions for this problem. In one we use list comprehension and in the other we use a sorted() function. Find the code for each solution in the button below:
Hi guys, I show my code here:
#Definir Tupla
numbers = (10, 5, 8, 20, 15)
#Convertir tupla en lista
numbers = list(numbers)
#Ordenar de mayor a menor
numbers.sort()
#Eliminar valores duplicados
uniques_values = list(set(numbers))
#Impresion
print(uniques_values[-2])
I included an instruction to remove duplicate values only per creative
This function efficiently finds the second largest number in a single pass through the tuple, without sorting or modifying the original data. It has a time complexity of O(n), where n is the number of elements in the tuple.
def second_largest_in_tuple(t):
largest = second_largest = float('-inf')
for num in t:
if num > largest:
second_largest = largest
largest = num
elif num > second_largest and num != largest:
second_largest = num
return second_largest
# Example usage
numbers = (10, 5, 8, 20, 15)
result = second_largest_in_tuple(numbers)
print(result) # Output: 15