Using itertools (2)

In the first article of this row I introduced to make combinations smartly using itertools. This time I’ll focus in filtering them. Again itertools is the key.

Let’s see it

for filter in self.filters:
            f = filter['function']
            args = filter['args']
            kwargs = filter['kwargs']
            valid_combs = itertools.ifilter(lambda x: f(x, *args, **kwargs), valid_combs)

In this code self.filters hold a list of dicts. This is part of the pluggable filtering system in pyeuromillions, but the key line is last. ifilter method return all items in seq that pass a test (in this case the lambda function). You can use ifilterfalse in a similar way but it’d return all items failing a test.

It performance really good. In less than 10 seconds it generates all combinations of 5 numbers between 1 and 50 having 3 even numbers in my actual computer (which is not a supercomputer).

Next time I spent some time writing pyeuromillions code I’ll focus in create a set of filtering functions.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: