3

Hello I want to find the first index of the max and min value of an array of integer.

my code returns all the index in case of duplicate values ...

A= [1,1,8,7,5,9,6,9]
def minmaxloc(num_list):
  for i,y in enumerate(num_list):
    if y ==max(num_list) or y==min(num_list):
      print i
minmaxloc(A)

output: 0 1 5 7

what i want : (0,5)

thanks for your help.

bryan tetris
  • 123
  • 1
  • 3
  • 7
  • 1
    `import numpy as np; (np.argmin(A),np.argmax(A))` – anishtain4 May 11 '18 at 18:19
  • The top answer in the question you were pointed to isn't that great since it sweeps over the array potentially twice. The 2nd answer, https://stackoverflow.com/a/2474238/500207 is better in this regard. Ideally you'd be able to calculate the max and min in a single sweep, but neither Python or Numpy provide a `minmax` :( – Ahmed Fasih May 11 '18 at 18:22

2 Answers2

2
def minmaxloc(num_list):
    return num_list.index(max(num_list)), num_list.index(min(num_list))

print(minmaxloc(a))
ktzr
  • 1,625
  • 1
  • 11
  • 25
1

Use numpy's argmin and argmax methods:

import numpy as np
def minmaxloc(num_list):
    return np.argmin(num_list), np.argmax(num_list)
A= [1,1,8,7,5,9,6,9]
print(minmaxloc(A))
Merlin1896
  • 1,751
  • 24
  • 39