Added any/all sequence predicates.

This commit is contained in:
Jeremy Fincher 2003-08-23 12:08:14 +00:00
parent 6c26e4e28f
commit a7826bdc34
2 changed files with 32 additions and 2 deletions

View File

@ -186,4 +186,23 @@ def flip((x, y)):
"""Flips a two-tuple around. (x, y) becomes (y, x)."""
return (y, x)
def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
if p is None:
p = bool
for elt in seq:
if p(elt):
return True
return False
def all(p, seq):
"""Returns true if all elements in seq satisfy predicate p."""
if p is None:
p = bool
for elt in seq:
if not p(elt):
return False
return True
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:

View File

@ -1,7 +1,6 @@
#!/usr/bin/env python
###
# Copyright (c) 2002, Jeremiah Fincher
### # Copyright (c) 2002, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@ -116,5 +115,17 @@ class FunctionsTest(unittest.TestCase):
self.assertEqual(lflatten([1, [2, [3, 4], 5], 6]), [1, 2, 3, 4, 5, 6])
self.assertRaises(TypeError, lflatten, 1)
def testAny(self):
self.failUnless(any(lambda i: i == 0, range(10)))
self.failIf(any(None, range(1)))
self.failUnless(any(None, range(2)))
def testAll(self):
self.failIf(all(lambda i: i == 0, range(10)))
self.failUnless(any(lambda i: i % 2, range(2)))
self.failIf(any(lambda i: i % 2 == 0, [1, 3, 5]))
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: