[英]Why we have to define variable dp = [0] * (n+1) just to set its variable equal to 0( In Dynamic Programming)
我有一些关于某人定义的问题: dp = [0] * (n + 1)
只是为了将变量设置为 0,它想做什么?
In Python you can multiply a list and tuple with an integer n .在 Python 中,您可以将列表和元组与整数n相乘。 It will then generate a list or tuple with a length l×n with l the length of the given list/tuple.然后它将生成一个长度为l×n的列表或元组,其中l为给定列表/元组的长度。 It will repeat the elements in that collection, like:它将重复该集合中的元素,例如:
>>> [1,4,2,5]*3
[1, 4, 2, 5, 1, 4, 2, 5, 1, 4, 2, 5]
>>> (1,4,2,5)*3
(1, 4, 2, 5, 1, 4, 2, 5, 1, 4, 2, 5)
Since here the given list is a singleton, you thus construct a list with length n+1
where each element is 0
, like:由于这里给定的列表是一个单例,因此您可以构造一个长度为n+1
的列表,其中每个元素都是0
,例如:
>>> [0] * (5 + 1)
[0, 0, 0, 0, 0, 0]
When you multiply a list/tuple with an integer, the references of the items are coped.当您将列表/元组与整数相乘时,项目的引用将得到处理。 You thus do not make a "deep copy" of the values.因此,您不会对这些值进行“深层复制”。 Since int
s are immutable, that does not matter.由于int
是不可变的,这无关紧要。 But if the elements are lists for example, you did not make copies of that list, you made a list where you referenced the same list multiple times.但是,例如,如果元素是列表,则您没有制作该列表的副本,而是制作了一个多次引用同一个列表的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.