Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, lambda, find minimum

Tags:

python

lambda

I have foreach function which calls specified function on every element which it contains. I want to get minimum from thise elements but I have no idea how to write lambda or function or even a class that would manage that. Thanks for every help.


I use my foreach function like this:
o.foreach( lambda i: i.call() )

or

o.foreach( I.call )

I don't like to make a lists or other objects. I want to iterate trough it and find min.

I manage to write a class that do the think but there should be some better solution than that:

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 suppose that my .foreach method is non-python idea. I should do my Class iterable because all your solutions are based on lists and then everything will become easier.

In C# there would be no problem with lambda function like that, so I though that python is also that powerful.

like image 712
qba Avatar asked Oct 27 '09 22:10

qba


1 Answers

Python has built-in support for finding minimums:

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

If you need to process the list with a function first, you can do that with map:

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

Or you can get fancy with list comprehensions and generator expressions, for example:

>>> min(double(x) for x in [1, 2, 3])
2
like image 187
Ryan Bright Avatar answered Nov 15 '22 06:11

Ryan Bright