how can i make np.argmin code without numpy?
Asked Answered
P

2

6

I've been given the challenge to code np.argmin without numpy .

I've been thinking hard for about a day.. I have no idea whether I should use a for statement,

an if statement, a while statement, or another function..


First question!

First, I thought about how to express it with an inequality sign to distinguish between cases.

using the if statement

a[0,0] - a[0,1] > 0

a[0,0] - a[0,1] < 0

I tried to write the code by dividing the two cases.

There were too many cases, so I stopped.

Couldn't it be done with an If statement?


Second question!

We know that the argmin method represents the address of a pointer as an array value.

What is in the screen capture is what I arbitrarily input as a two-dimensional list.

ndarray.

Because the task is limited to receiving a two-dimensional list as input

I thought that the directions of axis=0 and axis=1 are fixed.

Then axis=0 freezes the column and compares row to row

Is it okay to think that axis=1 freezes rows and compares columns to columns?


Third question!

After receiving an arbitrary two-dimensional list, ndarray is

I thought it would be in the form of a matrix of the form ixj.

Then, if you use a.shape, the output value is output as (i , j).

How can we extract i and j here?


It's really hard to think about all day long. Any hints would be appreciated.

Pigweed answered 8/1, 2022 at 10:33 Comment(2)
Any time you iterate through a lust you can use enumerate to get the index as well. min works on lists. Lists also have a index (or is find) method.Neckar
Stick to asking 1 question at a time. You can ask separate questions to avoid being flagged as needing more focus.Rouleau
D
14
def argmin(a):
    return min(range(len(a)), key=lambda x : a[x])
def argmax(a):
    return max(range(len(a)), key=lambda x : a[x])

This code is for 1D list.

Distribute answered 26/6, 2022 at 3:30 Comment(1)
Ran a little benchmark and found that if we change key=lambda x : a[x] to key=a.__getitem__ we can have ~40% speedupGel
P
0

In order to accept an iterator argument like

>>> argmin(range(-2, 3))
0

the answer from @wannik can be modified by considering the comment about enumerate from @hpaulj

argmin = lambda vals: min(enumerate(vals), key=lambda nv: nv[1])[0]
Parry answered 15/8 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.