Statement
Solution
Python Exercise 4.1: Min/Max Finder
Lists are used to store multiple items in a single variable. Your task is to find the largest and smallest numbers in a list without using Python's built-in min() or max() functions.
Your program should:
- Create a list with at least 10 numbers (you can generate them randomly or hardcode them).
- Initialize a variable
minimumandmaximumusing the first item in the list. - Loop through the list starting from the second item.
- Update
minimumif the current number is smaller. - Update
maximumif the current number is larger. - Print the results.
Sample Interaction:
Input
Output
(None)
List: [12, 45, 2, 67, 34, 89, 10, 5, 99, 23]
Smallest Number: 2
Largest Number: 99
Solution
By comparing every number against our current "best" found so far, we can determine the min and max manually.
import random
# 1. Create a list of 10 random numbers (1-100)
numbers = []
for i in range(10):
numbers.append(random.randint(1, 100))
print(f"List: {numbers}")
# 2. Initialize min and max with the first element
minimum = numbers[0]
maximum = numbers[0]
# 3. Iterate through the list
for num in numbers:
if num < minimum:
minimum = num
if num > maximum:
maximum = num
# 4. Print results
print(f"Smallest Number: {minimum}")
print(f"Largest Number: {maximum}")
Key Concepts:
list[0]accesses the first element.append()adds items to the end of a list.- We assume the first number is both the min and max until we find evidence to the contrary.
Test Console
Run code to see output...