def any(iterable, predicate): """ #returns True if predicate returns True for at least 1 item in iterable >>> any([1,3,5,8], lambda n: (n%2 == 0)) True >>> any([1,3,5,8], lambda n: (n > 4)) True >>> any([1,3,5,8], lambda n: (n < 1)) False """ for ele in iterable: if predicate(ele): return True return False def none_of(iterable, predicate): #returns True if predicate returns False for all items """ >>> none_of([1,3,5,7], lambda n: (n%2 == 0)) True >>> none_of([1,3,5,8], lambda n: (n%2 == 0)) False """ for ele in iterable: if predicate(ele): return False return True def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
Monday, May 14, 2012
Writing higher order functions in Python
This article will show you how easy it is to write your own higher order functions including test cases
Labels:
Python
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment