Luke
Luke

Reputation: 51

Finding the minimum value for different variables

If i am doing some math functions for different variables for example:

a = x - y
b = x**2 - y**2
c = (x-y)**2
d = x + y

How can i find the minimum value out of all the variables. For example:

a = 4
b = 7
c = 3
d = 10

So the minimum value is 3 for c. How can i let my program do this.

The problem is if i append a,b,c,d to a list i have to do something like:

lst.append((a,b,c,d))

This makes the list to be - [(4,7,3,10)]

making all the values relating to one index only ( lst[0] )

If possible is there any substitute to do this or any way possible as to how can i find the minimum!

LNG - PYTHON

Thank you

Upvotes: 0

Views: 5104

Answers (4)

Michael
Michael

Reputation: 13934

The buiit-in function min will do the trick. In your example, min(a,b,c,d) will yield 3.

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304503

You can find the index of the smallest item like this

>>> L = [4,7,3,10]
>>> min(range(len(L)), key=L.__getitem__)
2

Now you know the index, you can get the actual item too. eg: L[2]

Another way which finds the answer in the form(index, item)

>>> min(enumerate(L), key=lambda x:x[1])
(2, 3)

I think you may be going the wrong way to solving your problem, but it's possible to pull values of variable from the local namespace if you know their names. eg.

>>> a = 4
>>> b = 7
>>> c = 3
>>> d = 10
>>> min(enumerate(['a', 'b', 'c', 'd']), key=lambda x, ns=locals(): ns[x[1]])
(2, 'c')

a better way is to use a dict, so you are not filling your working namespace with these "junk" variables

>>> D = {}
>>> D['a'] = 4
>>> D['b'] = 7
>>> D['c'] = 3
>>> D['d'] = 10
>>> min(D, key=D.get)
'c'
>>> min(D.items(), key=lambda x:x[1])
('c', 3)

You can see that when the correct data structure is used, the amount of code required is much less.

Upvotes: 3

Oleg Melnikov
Oleg Melnikov

Reputation: 3298

pack as dictionary, find min value and then find keys that have matching values (possibly more than one minimum)

D = dict(a = 4, b = 7, c = 3, d = 10)
min_val = min(D.values())
for k,v in D.items():
    if v == min_val: print(k)

Upvotes: 0

Alberto Bonsanto
Alberto Bonsanto

Reputation: 18042

If you store the numbers in an list you can use a reduce having a O(n) complexity due the list is not sorted.

numbers = [999, 1111, 222, -1111]
minimum = reduce(lambda mn, candidate: candidate if candidate < mn else mn, numbers[1:], numbers[0])

Upvotes: 1

Related Questions