如果if语句中包含这样的内容if T[x,y]:并帮助解释动态表cod,这意味着什么

2024-04-26 10:43:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图学习一些关于动态编程的知识,并且有一段代码可以创建一个数据表,但是我很难弄清楚某些部分是做什么的。在

代码如下:

from collections import defaultdict


data = [1, 2, 4]
sum = 10

# T[x, i] is True if 'x' can be solved
# by a linear combination of data[:i+1]
T = defaultdict(bool)           # all values are False by default
T[0, 0] = True                # base case

for i, x in enumerate(data):    # i is index, x is data[i]
    #print i, x
    for s in range(sum + 1): #set the range of one higher than sum to include sum itself
        #print s
        for c in range(s / x + 1):  
            if T[s - c * x, i]:
                T[s, i + 1] = True

我慢慢地开始弄清楚这段代码是如何工作的,但是最后第二行if{}有点困难,因为我无法在终端中完全复制它。当我输入simlair(使用值)时,它会创建一个类似于[1,2]的矩阵,但是它怎么可能是真是假呢,这样它就可以进入下面的语句了?在

如果有帮助的话,它是一些代码的一部分,可以帮助分解数字。所以我想把1,2,4分解成10。在这个问题Can brute force algorithms scale?中,有人建议我创建一个动态表来引用。在

以下是最终结果(我无法解释结果):

^{pr2}$ 太好了!在

谢谢!在


Tags: of代码intruefordatabyif
2条回答

我不确定我完全不理解这个问题。在

如果元组(x, y)存在于字典T中,那么{}将根据保存到它的内容返回True或{}。如果(x, y)不存在,because of ^{},则不存在的键将导致调用bool(),这将返回False。您可以将bool替换为一些自定义函数以使其更清楚

>>> from collections import defaultdict
>>> def on_missing():
...     print("missing key!")
...     return 'empty!'
... 
>>> T = defaultdict(on_missing)
>>> T[0, 0] = True     # Store 'True' for key (0, 0) in T
>>> T[0, 0]            # Retrieve the stored value
True
>>> T[1, 2]            # (1, 2) does not exist, so call on_missing()
missing key!
'empty!'       
>>> T[1, 2] = True     # Now store a value for (1, 2)
>>> T[1, 2]            # We can see 'True' is stored.
True

因为您只分配True,所以条件{}基本上就是检查{}是否被手动分配。通常我们会使用一个set()。在

我不太明白你的问题,但这里的语法似乎很简单。T是defaultdict,所以T[s-c*x,i]通过键访问值,其中key是(s-c*x,i)。默认情况下,T中的所有值都是False,代码在最后一行将其中一些值更新为True。在

相关问题 更多 >