简体   繁体   中英

How do I generate addends for a given sum using Python?

I'm trying to generate the possible addends for any number between 0 and 30. The number of addends = 10, lower addend limit = 0, and upper addend limit = 3.

For example, for the number 30, the addends can be 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3 = 30.

For 12, the addends can be, 3 + 3 + 1 + 2 + 1 + 1 + 0 + 0 + 1 = 12, or 3 + 3 + 3 + 3 + 3 + 0 + 0 + 0 + 0 = 12 or anything within the given limit. But the number of addends should always be 10.

Recursively create a tree with a branch for each of your possible values between the lower and upper limits (so in your case each branch with have 4 leaves for each of [0, 1, 2, 3] . Your recursion base cases are that you're either deeper than levels 10 into the tree or that you've got the sum you want (in which case return it) or you've exceeded the sum (in which case return nothing). Assuming the order is significant (ie 3+1 is a distinct answer from 1+3 ), that's it. I don't have time to code it for you.

Or, since you're working with small numbers, you can just brute force it by generating all 1,048,576 ways to chose 10 elements from [0, 1, 2, 3] and check which ones sum to what you want

from itertools import product

def addend_all(n):
    for combination in product(range(4), repeat=10):
        if sum(combination) == n:
            yield combination

for i in range(31):
    print(list(addend_all(i)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM