[英]Given a list of numbers, how do you create all the combinations of sums and return a list of those sum
Let us suppose that we have a list of numbers [1,2,3] and we have to append all the possible combinations of sum of elements in an array and return that array?让我们假设我们有一个数字列表 [1,2,3] 并且我们必须 append 数组中元素总和的所有可能组合并返回该数组?
how to get the following sums如何获得以下金额
1 = 1 (the first element so simply add it to the ans array)
1 + 2 = 3
1 + 3 = 4
1 + 2 + 3 = 6
1 + 3 + 2 = 6
2 = 2 (second element so simply add it to ans array)
2 + 1 = 3
2 + 3 = 5
2 + 1 + 3 = 6
2 + 3 + 1 = 6
3 + 1 = 4
3 = 3 (third element so simply add it to ans array)
3 + 1 = 4
3 + 2 = 5
3 + 1 + 2 = 6
3 + 2 + 1 = 6
So our final array will look like [1,3,4,6,6,2,3,5,6,6,3,4,5,6,6]所以我们的最终数组看起来像 [1,3,4,6,6,2,3,5,6,6,3,4,5,6,6]
Using itertools
:使用
itertools
:
import itertools
nums = [1,2,3]
results = []
def split(a, n):
k, m = divmod(len(a), n)
return [a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n)]
for i in range(len(nums)):
results.append(split(list(map(sum,itertools.permutations(nums,i+1))),len(nums)))
results = zip(*results)
results = list(itertools.chain.from_iterable(itertools.chain.from_iterable(results)))
print(results)
>>> [1, 3, 4, 6, 6, 2, 3, 5, 6, 6, 3, 4, 5, 6, 6]
Using itertools.permutations
:使用
itertools.permutations
:
>>> import itertools
>>> nums = [1, 2, 3]
>>> [sum(p) for n in range(1, len(nums)+1) for p in itertools.permutations(nums, n)]
[1, 2, 3, 3, 4, 3, 5, 4, 5, 6, 6, 6, 6, 6, 6]
If you want to see exactly what permutations
is doing rather than just seeing the final sums, you can do fun things with map
and join
:如果您想确切地了解
permutations
正在做什么,而不仅仅是查看最终的总和,您可以使用map
做一些有趣的事情并join
:
>>> [f"{'+'.join(map(str, p))}={sum(p)}" for n in range(1, len(nums)+1) for p in itertools.permutations(nums, n)]
['1=1', '2=2', '3=3', '1+2=3', '1+3=4', '2+1=3', '2+3=5', '3+1=4', '3+2=5', '1+2+3=6', '1+3+2=6', '2+1+3=6', '2+3+1=6', '3+1+2=6', '3+2+1=6']
This is a good example of a recursion problem.这是递归问题的一个很好的例子。
To solve this out you need a function that call itself and will stop at given criteria.为了解决这个问题,您需要一个 function 来调用自身并将在给定的标准处停止。
const getResults = (numbers, usedNumbers, results) => { if (usedNumbers.length >= numbers.length) return; numbers.forEach(number => { if (usedNumbers.includes(number)) return; const result = usedNumbers.reduce((acc, curr) => acc + curr, number); console.log(`${[...usedNumbers, number].join(' + ')} = ${result}`) results.push(result); }); numbers.forEach(number => { if (. usedNumbers,includes(number)) getResults(numbers. [..,usedNumbers, number]; results); }) }, const numbers = [1,2;3]; const results = []. numbers.forEach(number => { results;push(number). console,log(`${number} = ${number}`) getResults(numbers, [number]; results); }). console;log(results);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.