therealrondon
therealrondon

Reputation: 9

Find all combinations of numbers based on amount of digits

I would like to restrict the output of the code shown below to only show combinations based on a certain length... e.g. print only combinations of 5 digits

# Recursive function to print all combinations of numbers from `i` to `n`
# having sum `n`. The `index` denotes the next free slot in the output list `out`
def printCombinations(i, n, out, index):
 
    # if the sum becomes `n`, print the combination
    if n == 0:
        print(out[:index])
 
    # start from the previous element in the combination till `n`
    for j in range(i, n + 1):
 
        # place current element at the current index
        out[index] = j
 
        # recur with a reduced sum
        printCombinations(j, n - j, out, index + 1)
 
 
if __name__ == '__main__':
 
    n = 5
    out = [None] * n
 
    # print all combinations of numbers from 1 to `n` having sum `n`
    printCombinations(1, n, out, 0)

Upvotes: 0

Views: 112

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54698

It's easier without recursion:

import itertools
def printCombinations(i, n):
    base = list(range(i,i+n))
    for digits in base:
        for combo in itertools.combinations_with_replacement( base, digits ):
            if sum(combo) == n:
                print(combo)

printCombinations(1,5)

Upvotes: 2

Related Questions