How to find the minimum value without using the min or max methods.
Repeat the comparison of the two elements.
** ▼ When finding the minimum value ** ・ First element: The initial value is the 0th value. This is the current minimum value.
Replace the smaller one with the current minimum value compared to the second element.
・ Second element: The next element. Move up one by one. It is always compared to the current minimum.
python
def min_val(arr):
  min = 0  #For the first time, set the 0th to the current minimum value (specified by the sequence number)
  for i in range(1, len(arr)):
    if arr[min] > arr[i]:  #If the next number is smaller in comparison, replace the current lowest sequence number.
      min = i
  print(a[min])
python
a = [2,4,5,3,10,1,8,6,3,2]
min_val(a)
#1
python
def max_val(arr):
  max = 0
  for i in range(1, len(arr)):
    if arr[max] < arr[i]:
      max = i
  print(a[max])
python
a = [2,4,5,3,10,1,8,6,3,2]
max_val(a)
#10
        Recommended Posts