Print Each Combination in Shell

Viewed 43

If you have a range of numbers from 1-49 with 6 numbers to choose from, there are nearly 14 million combinations. Using my current code (below), I have only 85,805 combinations remaining. I want to get all those 85,805 combinations to print into the Python shell showing every combination rather than the number of combinations possible as I'm currently seeing. Is that possible? Here's my code:

import functools

_MIN_SUM     = 152
_MAX_SUM     = 152
_MIN_NUM     = 1
_MAX_NUM     = 49
_NUM_CHOICES = 6
_MIN_ODDS    = 2
_MAX_ODDS    = 4

@functools.lru_cache(maxsize=None)
def f(n, l, s = 0, odds = 0):
    if s > _MAX_SUM or odds > _MAX_ODDS:
        return 0
    if n == 0 :
        return int(s >= _MIN_SUM and odds >= _MIN_ODDS)
    return sum(f(n-1, i+2, s+i, odds + i % 2) for i in range(l, _MAX_NUM+1))
          
result = f(_NUM_CHOICES, _MIN_NUM)

print('Number of choices = {}'.format(result))

Thank you!

1 Answers

Printing to the console is rather slow. You might want to print it to a file instead.

print("Hello World")
# vs
with open("file.txt", "w") as f:
    print("Hello World", file=f)

Try using for loops and recursion together:

def combinations(base, numbers, placesRemaining):
    out = []

    for i in numbers:
        if placesRemaining <= 1:
            out.append(base*i)
        else:
            out.extend(combinations(base*i, numbers, placesRemaining-1))
    
    return out

places = 6
numbers = range(1, 50)
answer = combinations(1, numbers, places)

That solution is not likely to run into the recursion limit, as the maximum recursion depth is equal to places. I did not run this on the full problem, but it performed well on smaller ones. Altering the starting base will multiply every number you calculate by that number, so I do not recommend it.

Related