The task is to find the maximum and minimum elements in a list without utilizing any built-in functions.
def find_max_min(numbers):
max_num = min_num = numbers[0]
for num in numbers[1:]:
if num > max_num:
max_num = num
elif num < min_num:
min_num = num
return max_num, min_num
# Example usage
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
max_value, min_value = find_max_min(numbers)
print("Max:", max_value, "Min:", min_value)
Let’s break down the above implementation :
- Function Definition: The function
find_max_min
takes a single argument,numbers
, which is expected to be a list of numerical values. - Initialization: The first element of the list is assigned to both
max_num
andmin_num
. - Iteration: A for loop iterates through the list starting from the second element, comparing each number to the current maximum and minimum.
- Comparison Logic: Conditional statements update the maximum and minimum values based on comparisons.
- Return Statement: The function returns a tuple containing the maximum and minimum values.