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.