合并两个列表并递归排序 [英] combine two list and sort recursively
本文介绍了合并两个列表并递归排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试定义一个名为 combine 的函数,以将两个列表作为参数并递归地将它们组合成一个排序列表.
I'm trying to define a function named combine to take two lists as parameters and combine them into one sorted list recursively.
def combine (l1,l2):
if l1 == []:
return l2
elif l2 == []:
return l1
elif l1 == [] and l2 == []:
return []
sort_l = []
index = 0
for num in l1:
if num <= l2[0]:
sort_l.append(num)
index += 1
else:
return combine(l2, l1[index:])
return sort_l + l2
它给了我:
combine([1,3,5,7,9],[0,2,4,6,8]) -> [8, 9]
但应该:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
有什么建议吗???
推荐答案
你的方法是正确的.但是,您要在每次递归调用中重新分配 sort_l
.您需要在函数外部定义它或在每次函数调用时传递它,只创建一次:
Your approach is correct. But, you are reallocating the sort_l
in every recursive call. You need to either define it outside the function or pass it with every function call, after creating only once:
sort_l = []
def combine (l1,l2):
if l1 == []:
return l2
elif l2 == []:
return l1
elif l1 == [] and l2 == []:
return []
index = 0
for num in l1:
if num <= l2[0]:
sort_l.append(num)
index += 1
else:
return combine(l2, l1[index:])
return sort_l + l2
或
def combine (l1,l2, sort_l=None):
if sort_l is None:
sort_l = []
if l1 == []:
return l2
elif l2 == []:
return l1
elif l1 == [] and l2 == []:
return []
index = 0
for num in l1:
if num <= l2[0]:
sort_l.append(num)
index += 1
else:
return combine(l2, l1[index:], sort_l) # pass it here
return sort_l + l2
combine([1,3,5,7,9],[0,2,4,6,8]) # Don't pass any list, it will be created in first call.
这篇关于合并两个列表并递归排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文