python-3.x - 在列表名称 sub_num 中,python 中的 sub_num = [*(sub_num[:]),i] 和 sub_num.append(i) 有什么区别,应该首选什么
问题描述
我正在尝试解决 bestSum 问题,它基本上找到了加到目标值的元素的最小数量,以下似乎工作正常,只有当使用 sub_num = [*(sub_num[:]),i]
添加i
到sub_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]
也请让我知道是否有任何其他方法可以改进此代码
解决方案
推荐阅读
- c - C regexec 找不到与简单贪婪正则表达式的最长匹配
- ruby - 无法放弃工作目录中的更改
- bash - 如何在 bash while 循环中进行算术运算?
- python - 如何像在python中一样在c++中打印完整的整数?
- javascript - 如何使用类名在页面的一侧设置自动滚动?
- ruby-on-rails - Rspec:如何测试私有方法中引发的异常?
- mysql - MySQL -Pentaho 从模式获取视图时出错 [null]
- ios - 表格视图不附加表格视图单元格
- android - 内部类的意图(SettingsActivity)
- linux - Docker - 在 Centos 中提取时出错(无效的 tar 标头)