问题
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
It gives me:
combine([1,3,5,7,9],[0,2,4,6,8]) -> [8, 9]
but should:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Any advice???
回答1:
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
or
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.
回答2:
python lists can be combined with a simple +
and the builtin function sorted() will sort items in the list for you.
sorted(l1 + l2) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
回答3:
program should be like this:
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
print(combine([1,3,5,7,9],[0,2,4,6,8]))
回答4:
You're close. The trick is to put the smaller of l1[0]
and l2[0]
in front of the result of the recursive combine()
:
def combine (l1,l2):
if l1 == []:
return l2
if l2 == []:
return l1
if l1[0] <= l2[0]:
return [l1[0]] + combine(l1[1:], l2)
return [l2[0]] + combine(l1, l2[1:])
来源:https://stackoverflow.com/questions/36990057/combine-two-list-and-sort-recursively