首页 > 解决方案 > 在列表名称 sub_num 中,python 中的 sub_num = [*(sub_num[:]),i] 和 sub_num.append(i) 有什么区别,应该首选什么

问题描述

我正在尝试解决 bestSum 问题,它基本上找到了加到目标值的元素的最小数量,以下似乎工作正常,只有当使用 sub_num = [*(sub_num[:]),i]添加isub_num列表而不是使用sub_num.append(i) 我知道一个正在使用deepcopy而另一个不是,但不管怎样,我希望使用sub_num.append(i)方法得到相同的结果

memo = {}
def how_sum(n,numbers):
    if(n in memo):
        return memo[n]
    elif(n == 0):
        return []
    elif(n < 0):
        return None
    
    shortestcombination = None

    for i in numbers:
        sub_num = how_sum(n-i,numbers)
        if ( sub_num != None ):
            memo[n]= sub_num[:]
            sub_num.append(i)         #<-commenting this line and 
            #sub_num = [*(sub_num[:]),i]    <-uncommenting this would give me correct ans
            if( (shortestcombination == None) or (len(sub_num) < len((shortestcombination)))):
                shortestcombination = sub_num[:]

    if(shortestcombination != None):
        memo[n] = shortestcombination[:]
    else:
        memo[n] = None
    
    return shortestcombination


print(how_sum(7,[7])) 
memo.clear()
print(how_sum(100, [1,2,5,25]))# ans should be [25,25,25,25]
memo.clear()

使用附加给我[25, 2, 5, 25, 2, 5, 25, 2, 5, 25]作为输出而不是[25,25,25,25]第二个测试用例,但如果我使用,我会得到正确的答案sub_num = [*(sub_num[:]),i]

也请让我知道是否有任何其他方法可以改进此代码

标签: python-3.xdynamic-programmingdeep-copyshallow-copy

解决方案


推荐阅读