Search code examples
pythonrangecombinationspython-itertools

All combinations in (range(1, 36), 7) with + conditions


I have a little python script what is giving back all 7 combinations of range(1, 36) and writting it to the txt file.

from itertools import combinations

f = open('combinations.txt', 'w')
for comb in combinations(range(1,36), 7):
    f.write(str(comb))
    f.write('\n')
f.close()

But becouse it would be a very big file I do not want to write those whose are 7 and 6 and 5 consecutive numbers.

For example:

  • 7 consecutive numbers: 1 2 3 4 5 6 7 and 2 3 4 5 6 7 8 and.. 29 30 31 32 33 34 35
  • 6 consecutive numbers: 1 2 3 4 5 6 +(one any other more) and.. 29 30 31 32 33 34 +(one any other more)
  • 5 ..

Any idea how can I do it? And how big would be my txt?


Solution

  • If I am not mistaken, you can do it like this:

    from itertools import combinations
    
    def count_consecutive(l):
        counts = [1]
        counts_index = 0
        for i in range(1, len(l)):
            if l[i] == l[i-1] + 1:
                counts[counts_index] = counts[counts_index] + 1
            else:
                counts.append(1)
                counts_index += 1
        return max(counts)
    
    f = open('C:/combinations.txt', 'w')
    for comb in combinations(range(1,36), 7):
        if count_consecutive(comb) not in [5, 6, 7]:
            f.write(str(comb))
            f.write('\n')
    f.close()
    

    It saves 12,615 of 6,724,520, which is like 0.18%, resulting in 180.5 MB file.