If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Wednesday, May 21, 2008

next_n

Suppose you want to find the next n elements of a stream the matches a predicate.

(I just used it in web scraping with BeautifulSoup to get the next 5 sibling "tr" for a table).
#!/usr/bin/env python

from itertools import ifilter, islice

def next_n(items, pred, count):
return islice(ifilter(pred, items), count)

if __name__ == "__main__":
from gmpy import is_prime
from itertools import count
for prime in next_n(count(1), is_prime, 10):
print prime
Will print
2
3
5
7
11
13
17
19
23
29
(Using gmpy for is_prime)

1 comment:

L said...

short and sweet :)

Blog Archive