加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

平衡两个列表,直到它们的总和相等,并在Python中的两个列表中进行

发布时间:2020-12-20 13:18:47 所属栏目:Python 来源:网络整理
导读:a = [70,30,33,23,4,34,95]b = [50,10,7] 我试过这个,但我知道这不够准确 if sum(a) sum(b): a.sort() b.sort() temp = [int(i) for i in a] i=0 while(sum(b) = sum(temp) and (i = len(a) - 1)): b.append(a[i]) temp.remove(a[i]) i = i+1 a = [int(i) fo
a = [70,30,33,23,4,34,95]
b = [50,10,7]

我试过这个,但我知道这不够准确

if sum(a) > sum(b):
   a.sort()
   b.sort()
   temp = [int(i) for i in a]
   i=0
   while(sum(b) <= sum(temp)  and (i <= len(a) - 1)):
      b.append(a[i])
      temp.remove(a[i])
      i = i+1

    a = [int(i) for i in temp]
if sum(b) > sum(a):
    a.sort()
    b.sort()
    temp = [int(i) for i in b]
    i=0
    while(sum(a) <= sum(temp)  and (i <= len(b) - 1)):
        a.append(b[i])
        temp.remove(b[i])
        i = i+1        

    b = [int(i) for i in temp]

结果是:

sums = 186,184

列表= [7,70,95,4],[4,50]

必填答案:

总和= 185,185

列表= [7,50,95],70]

解决方法

有些数字需要从a移动到b,有些数字需要从b移动到a.移动的数字集是两个列表中所有数字集的子集.在您的示例中,只有12个数字,这意味着2 ** 12 == 4096个子集.由于数量很少,蛮力方法应该会成功.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读