python - 将列表分成两部分,尽可能等于总和
问题描述
我正试图围绕这整个事情展开我的头脑,但我似乎无法弄清楚。基本上,我有一个整数列表。将这些 int 值加起来等于 15。我想将一个列表分成 2 部分,但同时,使每个列表在总和上尽可能接近。对不起,如果我不解释这个很好。
例子:
list = [4,1,8,6]
我想实现这样的目标:
list = [[8, 1][6,4]]
将第一个列表相加等于 9,另一个等于 10。这非常适合我想要的,因为它们尽可能接近。
我现在拥有的:
my_list = [4,1,8,6]
total_list_sum = 15
def divide_chunks(l, n):
# looping till length l
for i in range(0, len(l), n):
yield l[i:i + n]
n = 2
x = list(divide_chunks(my_list, n))
print (x)
但是,这只是将其分为两部分。
任何帮助,将不胜感激!
解决方案
您可以使用递归算法和列表的“蛮力”分区。从零的目标差异开始,逐渐增加您对两个列表之间差异的容忍度:
def sumSplit(left,right=[],difference=0):
sumLeft,sumRight = sum(left),sum(right)
# stop recursion if left is smaller than right
if sumLeft<sumRight or len(left)<len(right): return
# return a solution if sums match the tolerance target
if sumLeft-sumRight == difference:
return left, right, difference
# recurse, brutally attempting to move each item to the right
for i,value in enumerate(left):
solution = sumSplit(left[:i]+left[i+1:],right+[value], difference)
if solution: return solution
if right or difference > 0: return
# allow for imperfect split (i.e. larger difference) ...
for targetDiff in range(1, sumLeft-min(left)+1):
solution = sumSplit(left, right, targetDiff)
if solution: return solution
# sumSplit returns the two lists and the difference between their sums
print(sumSplit([4,1,8,6])) # ([1, 8], [4, 6], 1)
print(sumSplit([5,3,2,2,2,1])) # ([2, 2, 2, 1], [5, 3], 1)
print(sumSplit([1,2,3,4,6])) # ([1, 3, 4], [2, 6], 0)
推荐阅读
- xml - 获取元素文本未在 xml 文件中返回值
- python - python sqlite:在排序后查找列的一部分的平均值。(可能是熊猫)
- winforms - webview2 拒绝在 Visual Studio 2017 .net winforms 中工作
- apache - 间歇性无法连接到 shibd 进程,应通知站点管理员
- javascript - React/Redux 不渲染 nextState
- javascript - 新的 Chrome 行为:单击的元素保持在原处,并且在加载新内容时文档滚动位置移动
- arrays - 如何使用powershell将行转换为列
- javascript - 验证上传的 Word 模板 Javascript
- python-3.x - 使用 scipy.stats 将 Weibull 分布拟合到数据是否表现不佳?
- python-3.x - 如果使用 python 计算,JWT hs512 签名与 jwt.io 略有不同