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.