首页 > 解决方案 > 将作为响应返回的静态变量放在递归块中

问题描述

我写了这样一个递归解决方案来合并两个排序列表

res = []
def merge(l1, l2):
    """
    :type l1:List
    :rtype res: List[int]
    """
    #Base
    #Case1: Both are empty Case2 and Case3: One of them is empty
    if len(l1) * len(l2) == 0:
        res = l1 + l2 
        return res
    #Case 4    
    if len(l1) = 1 and len(l2) = 1:
        if l1[0] <= l2[0]:
            res.append(l1.pop(0)) #decrement 
        else:
            res.append(l2.pop(0))
        return res

    #Recur Case
    if len(l1) > 1 and len(l2) > 1:
        return merge(l1, l2)

我关心的问题是静态变量res应该在功能模块之外定义。res=[]在这种情况下,我可能会在其他地方重复使用时忘记复制。模块merge不是 100% 独立的。

所以我把它放在里面

def merge(l1, l2):
    """
    :type l1:List
    :rtype res: List[int]
    """
    global res
    try:
        print(res)
    except NameError:
        res = []
...

解法很繁琐,
怎么能简明扼要地解题呢?

标签: python

解决方案


您可以将res作为参数放入函数中。由于它是可变的,它也应该通过引用传递,并且不会占用更多内存(递归本身除外)。

或者您可以将它包装在一个类中并使用 访问它self.res,但这将提供与在递归中传递变量相同的逻辑,如下所示。

def merge(l1, l2, res=None):
    """
    :type l1:List
    :rtype res: List[int]
    """
    # Default parameter, read more here on why not to initialise as list
    # https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
    if res is None:
        res = []
    #Base
    #Case1: Both are empty Case2 and Case3: One of them is empty
    if len(l1) * len(l2) == 0:
        res = l1 + l2 
        return res
    #Case 4    
    if len(l1) = 1 and len(l2) = 1:
        if l1[0] <= l2[0]:
            res.append(l1.pop(0)) #decrement 
        else:
            res.append(l2.pop(0))
        return res

    #Recur Case
    if len(l1) > 1 and len(l2) > 1:
        return merge(l1, l2, res)

推荐阅读