缩短多重布尔运算以对两个排序列表进行排序

时间:2019-03-27 02:56:10

标签: python

我编写了以下递归解决方案以合并两个列表:

基本情况是:

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 个答案:

答案 0 :(得分:2)

您可以使用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)