Try to use itertools to make the code a bit easier to read.