Python lambda find minimum

I have a foreach function that calls the specified function for each element it contains. I want to get the minimum from these elements, but I have no idea how to write a lambda or function, or even a class that can handle this. Thanks for any help.


I use the foreach function as follows:
o.foreach( lambda i: i.call() )

or

o.foreach( I.call )

I do not like creating lists or other objects. I want to repeat it and find the mines.

I manage to write a class that thinks, but there must be some better solution than this:

class Min:                                           
    def __init__(self,i):                        
        self.i = i                              
    def get_min(self):                               
        return self.i                                
    def set_val(self,o):                             
        if o.val < self.i: self.i = o.val

m = Min( xmin )
self.foreach( m.set_val )                            
xmin = m.get_min()

Ok, so I believe my .foreach method is an idea other than python. I have to make my class iterable, because all your decisions are list-based, and then everything will become easier.

# -, , , python .

+5
6

foreach pythonic. , python, min.

, - :

def foreach(self, f):
    for d in self._data:
        f(d)

:

def __iter__(self):
    for d in self._data:
        yield d

min min(myobj).

+5

Python :

>>> min([1, 2, 3])
1

, map:

>>> def double(x):
...    return x * 2
... 
>>> min(map(double, [1, 2, 3]))
2

, :

>>> min(double(x) for x in [1, 2, 3])
2
+12

foreach . , min, , reduce , .

l = [5,2,6,7,9,8]
reduce(lambda a,b: a if a < b else b, l[1:], l[0])
+6

, : lambda . , def. :

lst = range(10)

print filter(lambda x: x % 2 == 0, lst)

def is_even(x):
    return x % 2 == 0

print filter(is_even, lst)

. . lambda ; def . filter() , .

, lambda , = lambda, def.

, , .foreach(), . Python min().

lst = range(10)
print min(lst)

EDIT: , , , . , , __iter__() .

+1

foreach, ,

, , , map.

, - :

min(map(f, seq))

f - , .

gnibbler, x , f(x) , :

min(seq, key=f)

... seq, f . , seq - ,

min(seq, key=len)

, , .

To list all the elements in the sequence for which the function freturns the smallest value, do the following:

values = map(f, seq)
result = [seq[i] for (i, v) in enumerate(values) if v == min(values)]
+1
source

Suppose you have

>>> seq = range(-4,4)
>>> def f(x):
...  return x*x-2

for the minimum value of f

>>> min(f(x) for x in seq)
-2

for x at minimum

>>> min(seq, key=f)
0

of course you can use lambda too

>>> min((lambda x:x*x-2)(x) for x in range(-4,4))
-2

but it's a little ugly, the map looks better here.

>>> min(map(lambda x:x*x-2, seq))
-2

>>> min(seq,key=lambda x:x*x-2)
0
0
source

All Articles