mirror of
https://github.com/Mikaela/Limnoria.git
synced 2024-12-23 11:12:47 +01:00
Added utils.iter.limited, an iterable that limits the number of elements that can be taken from another iterable.
This commit is contained in:
parent
c268aab9bd
commit
b5f1e2a3e7
@ -158,4 +158,15 @@ def startswith(long, short):
|
|||||||
except StopIteration:
|
except StopIteration:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def limited(iterable, limit):
|
||||||
|
i = limit
|
||||||
|
iterable = iter(iterable)
|
||||||
|
try:
|
||||||
|
while i:
|
||||||
|
yield iterable.next()
|
||||||
|
i -= 1
|
||||||
|
except StopIteration:
|
||||||
|
raise ValueError, 'Expected %s elements in iterable (%r), got %s.' % \
|
||||||
|
(limit, iterable, limit-i)
|
||||||
|
|
||||||
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
|
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
|
||||||
|
@ -384,6 +384,14 @@ class StrTest(SupyTestCase):
|
|||||||
|
|
||||||
|
|
||||||
class IterTest(SupyTestCase):
|
class IterTest(SupyTestCase):
|
||||||
|
def testLimited(self):
|
||||||
|
L = range(10)
|
||||||
|
self.assertEqual([], list(utils.iter.limited(L, 0)))
|
||||||
|
self.assertEqual([0], list(utils.iter.limited(L, 1)))
|
||||||
|
self.assertEqual([0, 1], list(utils.iter.limited(L, 2)))
|
||||||
|
self.assertEqual(range(10), list(utils.iter.limited(L, 10)))
|
||||||
|
self.assertRaises(ValueError, list, utils.iter.limited(L, 11))
|
||||||
|
|
||||||
def testRandomChoice(self):
|
def testRandomChoice(self):
|
||||||
choice = utils.iter.choice
|
choice = utils.iter.choice
|
||||||
self.assertRaises(IndexError, choice, {})
|
self.assertRaises(IndexError, choice, {})
|
||||||
|
Loading…
Reference in New Issue
Block a user