[英]Function to find a continuous sub-array which adds up to a given number in python
[英]a function that return all possible sub arrays that sum up to a specific given number (need not to be a continuous sub array)
当我做一些数学运算时,我遇到了这个问题,我需要找到给定数字的所有可能总和。 这是一个示例输入和 output 以便更好地理解问题。 假设我们得到一个数组arr=[1,2,3,4,5]
并且给定数字number=10
那么我需要这样的东西,
def solution(arr,number):
#you can code here
output: [1,2,3,4],[2,3,5],[1,5,4],[1,3,6],[1,6]
这是一个快速(经过测试)的答案:
import itertools
def solution(arr, number):
for i in range(len(arr)+1):
for s in list(itertools.combinations(arr, i)):
if sum(s) == number:
yield list(s)
arr = [ 1, 2, 3, 4, 5 ]
number = 10
print(list(solution(arr, number)))
印刷:
[[1, 4, 5], [2, 3, 5], [1, 2, 3, 4]]
使用动态规划算法求解
def solve(arr, s, i = None, path = None, solutions = None):
"""Use Dynamic Programming to find subsequence of arr
that sum to s
Arguments:
arr - array
i - current index that will use or not for arr
path - current subsequence we are summing
solutions - all solutions found
"""
# Set defaults
if i is None:
i = len(arr) - 1
if solutions is None:
solutions = []
if path is None:
path = []
# Base Cases
if s == 0:
solutions.append(path[:])
return solutions
if i < 0 or s < 0:
return
# Try with arr[i] in path
if arr[i] <= s:
solve(arr, s-arr[i], i-1, [arr[i]] + path, solutions)
# Try with arr[i] not in path
solve(arr, s, i-1, path, solutions)
return solutions
测试
arr = [1, 2, 3, 4, 5]
print(solve(arr, 10))
Output
[[1, 4, 5], [2, 3, 5], [1, 2, 3, 4]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.