简体   繁体   English

为什么我们必须定义变量 dp = [0] * (n+1) 只是为了将其变量设置为等于 0(在动态规划中)

[英]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.

相关问题 我们如何只用它的名字定义一个局部变量(用一个str) - How can we define a local variable just with its name(with a str) Python Class - 为什么在设置实例变量时我必须将我的 class 变量设置为等于自身 - Python Class - why do I have to set my class variable equal to itself when setting instance variable 是否有Python'快捷方式'来定义一个等于其自己名称的字符串版本的类变量? - Is there a Python 'shortcut' to define a class variable equal to a string version of its own name? 如何使输入等于变量 - How to have an input be equal to a variable 当我引入一个稍后将定义的变量时,我是否将它设置为等于 0? - When I introduce a variable that I will define later, do I set it equal to 0? 为什么我的硬币兑换(DP)功能中的变量发生变化? - Why is a variable in my coin-changing (DP) function changing? 制作动态变量集 - Making a dynamic variable set 有没有办法在不同的 class 中设置一个等于变量的值,并让它保持第一次运行的值而不必每次都运行? - Is there a way to set a value equal to a variable in a different class and have it keep the value from the first run and not have to run everytime? 我们可以在python中定义具有多个索引的变量吗? - can we define a variable with multi indices in python? 使用 python 的变量动态规划 Scope 用于子集问题 - Dynamic Programming Scope of Variable with python for the SubSets problem
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM