简体   繁体   中英

how to print elements of a list whose sum is equal to a given number in python?

Consider a list of numbers from 0 to 50. I want to print all the combinations of elements from that list whose sum is equal to any given number say 41. One combination is [4,5,7,9,16].I want to print other combinations like this.

@Anonymousss, check out this: (Note - the answer will give your a tuple pair - two numbers that add up to the target: 41, in this case)

This should work:

 from itertools import combinations

 nums = list(range(51))   # 0, 1, 2 to 50

 ans = [(x,y) for x, y in combinations(nums, 2) if x+y == 41]
>>> ans
[(0, 41), (1, 40), (2, 39), (3, 38), (4, 37), (5, 36), (6, 35), (7, 34), (8, 33), (9, 32), (10, 31), (11, 30), (12, 29), (13, 28), (14, 27), (15, 26), (16, 25), (17, 24), (18, 23), (19, 22), (20, 21)]

You can use combinations(...) function from itertools

import itertools

nums = range(51)
for n in range(1, len(nums) + 1):
    for p in itertools.combinations(nums, n):
        if sum(p) == 41:
            print(*p)

The following code is best used in a subroutine but it can be stand alone code.To change the average just change the number after the while loop. To change the amount of numbers change the amount of zeros in the lists. The random part can also be changed for the range of numbers.

def stats():
x =[0,0,0,0,0,0]
while mean(x) != 14.5:
    x =[0,0,0,0,0,0]
    for i in range(6):
        a = random.randint(9,17)
        x[i] = a
return x

The mean in this code is a separate subroutine that looks like this:

def mean(x):
y = sum(x)/6
return y

At the start of the code, you need to import the random library to allow the code to work properly. The only thing is that this code will only output one combination,such as:

stats() [11, 12, 16, 17, 16, 15]

You could write a recursive generator to efficiently produce only the combinations of positive integers that sum up to the target number:

def sumSets(numbers,target):
    if not target  : yield []
    if not numbers or target <= 0: return
    yield from sumSets(numbers[1:],target)
    yield from (numbers[:1]+ss for ss in sumSets(numbers[1:],target-numbers[0]))

nums = list(range(1,50,3))
for ss in sumSets(nums,41): print(ss)
      
[19, 22]
[16, 25]
[13, 28]
[10, 31]
[7, 34]
[4, 37]
[1, 40]
[1, 4, 7, 13, 16]
[1, 4, 7, 10, 19]  

Note that, if you're looking for all combinations of numbers from 1 to 50 that sum up to 41, you're going to get a lot of them:

nums = list(range(1,51))
print(sum(1 for _ in sumSets(nums,41))) # 1260

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