#
# python/examples/find1.py
#
# How to find the first item in a
# list for which a function is true
def find(f, seq):
"""
Return first item in sequence where f(item) == True.
Example 1:
>>> find( IsPrime , [ 4, 9, 13, 17 ] )
13
Example 2, using a function defined on the fly with 'lambda':
to find in the list 'codewords' the first element
whose attribute 'index' is equal to s,
>>> co = find(lambda p: p.index == s, codewords)
"""
for item in seq:
if f(item):
return item
def IsPrime( n ) :
"""
>>> IsPrime( 5 )
True
>>> IsPrime( 10 )
False
"""
for i in range(2,n) :
if (n%i == 0):
return False
return True
# Example by David MacKay www.aims.ac.za/~mackay/
# Solution from
# http://naeblis.cx/rtomayko/2004/09/13/
# cleanest-python-find-in-list-function
|