我编写了以下递归解决方案来合并两个列表:基本情况是:1) 断言两个列表都为空2)断言只有一个列表不为空3)减少大小写以删除元素4) 递归情况 def merge(l1, l2): """ :rtype: List """ global res res = [] #Base Cases #1 assert empty if len(l1) == 0 and len(l2) == 0: # return res #2assert one not empty if len(l1) == 0 and len(l2) != 0: return res.extend(l2) if len(l1) != 0 and len(l2) = 0: return res.extend(l1) #3assert one element in both if len(l1) = 1 and len(l2) = 1: if l1[0] < l2[0]: res.append(l1.pop()) res.append(l2.pop()) else: res.append(l2.pop()) res.append(l1.pop()) return res #4recur case else: return merge(l1, l2) 至于#2 assert only one is not emtty,就麻烦了,怎么能把逻辑讲的简洁明了呢?
1 回答
慕容708150
TA贡献1831条经验 获得超4个赞
您可以通过使用all()/any()和列表推导式来缩短代码,而不用打扰单独的变量res:
def merge(l1, l2)
if not all(l1, l2): # triggers when either l1 or l2 is empty
return l1 + l2 # no reason not to just concatenate an empty list
elif len(l1) == 1 and len(l2) == 1:
# ternary if statement
return [l1.pop(), l2.pop()] if l1[0] < l2[0] else [l2.pop(), l1.pop()]
else:
return merge(l1, l2)
添加回答
举报
0/150
提交
取消