Proposed new collection methods

Robert Kern rkern at ucsd.edu
Sun Aug 7 00:20:54 EDT 2005


Jeff Schwab wrote:
> Robert Kern wrote:
> 
>>Robert Kern wrote:
>>
>>>Christopher Subich wrote:
>>>
>>>>Dear Zeus no.  Find can be defined as:
>>>>def find(self, test=lambda x:1):
>>>>   try:
>>>>      item = (s for s in iter(self) if test(s)).next()
>>>>   except StopIteration:
>>>>      raise ValueError('No matching items in list')
>>>
>>>I would prefer that a find() operation return as soon as it locates an 
>>>item that passes the test. This generator version tests every item.
>>
>>Pardon me, I am retarded.
> 
> Why are you retarded?  Isn't the above code O(n)?
> 
> Forgive me for not understanding, I'm still awfully new to Python 
> (having come from Perl & C++), and I didn't see an explanation in the FAQ.

(s for s in iter(self) is test(s)) is a generator expression. It is 
roughly equivalent to

   def g(self, test=lambda x: True):
     for s in iter(self):
       if test(s):
         yield s

Now, if I were to do

   item = g(self, test).next()

the generator would execute the code until it reached the yield 
statement which happens when it finds the first item that passes the 
test. That item will get returned, and execution does not return to the 
generator again.

That implementation does indeed return as soon as it locates the first 
item, so yes, I was being retarded.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list