Using itertools (2)

July 9, 2011

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

Using itertools

June 1, 2011

Some time ago I wrote a snippet to make combinations in lottery games (49/6). I did it using six nested for loops, so it wasn’t the best approach. Now we have euromillions and I’m interested in doing same thing for this new game. But this time, I’ll use itertools.

Euromillions is quite simple. There are numbers and stars. A combination is valid if it contains 5 numbers (1,50) and 2 stars (1,9). In this first post, I’ll focus in, given a list of numbers and stars, generate all valid combinations with them.

The first step is to make all the available combinations with the numbers. Let’s assume self.numbers has a list of numbers between 1 and 50:

import itertools

valid_number_combs = itertools.combinations(self.numbers, 5)

Now we should do the same with stars. It’s pretty the same

import itertools

valid_number_stars = itertools.combinations(self.stars, 2)

Finally we should combine them using a cartesian product

valid_combs = itertools.product(valid_number_combs, valid_stars_combs)

And that’s all (folks). It’s pretty simple, but perfomance it’s great. In my personal computer it takes just 9 seconds to generate all available combinations with all numbers (1,50) and all stars (1,9). There are 76.275.360

Visit the github of the project for the code.

In the next post I’ll focus in provide high level filters such as limiting the number of odd/even numbers allowed in the same combination.