python将10到1递减_(Python)如何将3个递减列表合并成一个递减列表?

以下代码基于:

第一次左右合并得到中间结果

下一个合并中间结果和中间结果

代码

def Merge3Way(left,middle,right):

"""Takes three lists that are sorted in decreasing order and merges them into

one list ordered largest to smallest"""

# Step 1: Merge left & right

res_1 = []

left_ind, right_ind = 0, 0

while left_ind < len(left) and right_ind < len(right):

if left[left_ind] > right[right_ind]:

res_1.append(left[left_ind])

left_ind += 1

else:

res_1.append(right[right_ind])

right_ind += 1

for left_ind in range(left_ind, len(left)):

res_1.append(left[left_ind])

for right_ind in range(right_ind, len(right)):

res_1.append(left[right_index])

# Step 2: Merge intermediate result and middle

res_2 = []

res_ind, middle_ind = 0, 0

while res_ind < len(res_1) and middle_ind < len(middle):

if res_1[res_ind] > middle[middle_ind]:

res_2.append(res_1[res_ind])

res_ind += 1

else:

res_2.append(middle[middle_ind])

middle_ind += 1

for res_ind in range(res_ind, len(res_1)):

res_2.append(res_1[res_ind])

for middle_index in range(middle_ind, len(middle)):

res_2.append(middle[middle_ind])

return res_2

试验

result = Merge3Way([3,2,1],[6,5,4],[9,8,7])

print(result)

# Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值