子数组元素的总和等于 Python 中的目标值

编程入门 行业动态 更新时间:2024-10-24 16:29:46
本文介绍了子数组元素的总和等于 Python 中的目标值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我得到一个数组 arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 和一个目标值 trgt = 10.我需要找到 subarrays 的所有可能组合,这样每个子数组的元素总和将产生给定的目标值 trgt.我需要使用 Python 来完成任务.我在 here 中发现了类似的讨论.然而,给定的解决方案只返回一个可能的子数组,而不是其他有效的子数组.任何指向获取所有此类子数组的帮助都将非常有帮助.提前致谢.

I am given with an array arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and a target value trgt = 10. I need to find all possible combinations of subarrays such that sum of the elements of each subarray will result in the given target value trgt. I need to use Python to acomplish the task. I have found a similar discussion in here. However the given solution there only returns only one possible subarray instead of other valid subarrays. Any help pointing to obtaining all such subarrays will be very helpful. Thank you in advance.

推荐答案

获取组合的首选库是 itertools:

The library of choice for getting combinations is itertools:

import itertools as it import numpy as np arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] trgt = 10

首先计算可能导致 trgt 的元组的最大长度,即使它由可用的最小数字组成:

At first calculate the maximum length of a tuple that could result in trgt when summed up, even when it consists of the smallest numbers available:

maxsize = np.argwhere(np.cumsum(sorted(arr))>trgt)[0][0]

然后从1迭代到maxsize,让itertools创建对应的组合,只保存那些和trgt的组合:

Then iterate from one to maxsize, let itertools create the corresponding combinations and save only those which sum up to trgt:

subsets = [] for size in range(1, maxsize+1): subsets.extend([t for t in itbinations(arr, size) if sum(t)==trgt]) print(subsets) #[(10,), (1, 9), (2, 8), (3, 7), (4, 6), (1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5), (1, 2, 3, 4)]

更多推荐

子数组元素的总和等于 Python 中的目标值

本文发布于:2023-11-30 11:58:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649868.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目标值   数组   总和   元素   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!