Skip to content
Advertisement

recursive implementation of sum to target Python

I have the following method that, given a target integer, generates all ways to create that integer from an ordered row of integers, subject to the condition that the column index (starting from one) multiplied by the number sums to the target for each row.

Below is some code that achieves this.

JavaScript

Notice that all rows sum to target=7, i.e. take the bottom row 0*1 + 0*2 + 1*3 + 1*4=7.

In the general case, I do not know the number of columns that I require. For instance, I might simply have

JavaScript

or indeed, many more for loops.

How can I generalise this, most likely based on a recursive solution, so that the number of columns is a parameter?

Advertisement

Answer

Here is a recursive solution. You just run through the options for the last column, then fetch the combinations for whatever’s leftover using the remaining columns.

JavaScript

Output:

JavaScript

You can change it the call to (7,6) to see the difference.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement