
Finding the Maximum and Minimum Element in an Array
In this task, I worked on finding the minimum and maximum values from an array. Instead of writing everything in one place, I used a function to make the code cleaner and reusable. What I Did I created a function called find_min_max that takes an array as input and returns both the smallest and largest values. For example: Input: [1, 4, 3, 5, 8, 6] Output: [1, 8] How I Solved It First, I assumed that the first element of the array is both the minimum and maximum. Then I used a loop to go through each number in the array. While looping: If a number is smaller than the current minimum, I update the minimum If a number is larger than the current maximum, I update the maximum At the end, I return both values as a list. Code def find_min_max ( arr ): minimum = arr [ 0 ] maximum = arr [ 0 ] for num in arr : if num < minimum : minimum = num if num > maximum : maximum = num return [ minimum , maximum ] print ( find_min_max ([ 1 , 4 , 3 , 5 , 8 , 6 ])) print ( find_min_max ([ 12 , 3 , 15 , 7 ,
Continue reading on Dev.to Python
Opens in a new tab



