有两个长度一样的列表a和b,它们里面的元素都是整形的数值,要求:通过交换两个列表的元素,使得sum(a)和sum(b)的差最小
a = []
b = []
#自定义列表a和b
n = 0
while n < 5:
num1 = int(input('请输入列表a中的元素:'))
num2 = int(input('请输入列表b中的元素:'))
a.append(num1)
b.append(num2)
n += 1
#将两个列表合并为一个列表
Source = a
for i in b:
Source.append(i)
#将合并后的列表进行排序
Source.sort()
#定义两个新的空列表来存放元素
c = []
d = []
big = Source[-1]
next = Source[-2]
c.append(big)
d.append(next)
Source.remove(big)
Source.remove(next)
while Source != []:
if sum(c) > sum(d):
big = Source[-1]
next = Source[-2]
c.append(next)
d.append(big)
Source.remove(big)
Source.remove(next)
else:
big = Source[-1]
next = Source[-2]
c.append(big)
d.append(next)
Source.remove(big)
Source.remove(next)
a = c
b = d
print(a)
print(b)