Exercise
Function To Find Array's Min And Max Values
Objective
Develop a Python program that defines a function to find the smallest and largest numbers in a list. The function should accept the list as an input and use reference parameters to return the results. For example, if you pass a list like data = [1.5, 0.7, 8.0], after the function call, the minimum variable will hold the value 0.7 and the maximum will hold the value 8.0.
Example Python Exercise
Show Python Code
# Function to find the smallest and largest numbers in the list
def find_min_max(data, min_value, max_value):
# Initialize min_value and max_value to the first element in the list
min_value[0] = data[0] # Set the first element as the initial min_value
max_value[0] = data[0] # Set the first element as the initial max_value
# Iterate through the list to find the smallest and largest numbers
for num in data:
if num < min_value[0]:
min_value[0] = num # Update min_value if current number is smaller
if num > max_value[0]:
max_value[0] = num # Update max_value if current number is larger
# Example list of numbers
data = [1.5, 0.7, 8.0]
# Initialize the reference variables for min and max values
min_value = [float('inf')] # Start with a very large number as initial min_value
max_value = [float('-inf')] # Start with a very small number as initial max_value
# Call the function with the list and reference variables
find_min_max(data, min_value, max_value)
# Print the results
print(f"The smallest number is: {min_value[0]}") # Min value after function call
print(f"The largest number is: {max_value[0]}") # Max value after function call
Output
python min_max.py
The smallest number is: 0.7
The largest number is: 8.0
Share this Python Exercise