【发布时间】:2012-02-09 23:46:35
【问题描述】:
我在 python 中创建表时遇到问题。基本上我想建立一个表格,每个数字都告诉我是否可以用它来分解另一个数字(它的表格算法来自Can brute force algorithms scale? 中接受的答案)。这是伪代码:
for i = 1 to k
for z = 0 to sum:
for c = 1 to z / x_i:
if T[z - c * x_i][i - 1] is true:
set T[z][i] to true
这是我的python实现:
from collections import defaultdict
data = [1, 2, 4]
target_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]
for s in range(target_sum + 1): #set the range of one higher than sum to include sum itself
for c in range(s / x + 1):
if T[s - c * x, i]:
T[s, i+1] = True
#query area
target_result = 1
for node in T:
if node[0]==target_result:
print node, ':', T[node]
所以我期望的是,如果 target_result 设置为 8,它会显示列表 data 中的每个项目如何用于分解该数字。对于所有工作的 8、1、2、4,所以我希望它们都是真实的,但是这个程序正在使一切变为真实。例如,1 应该只能被 1(而不是 2 或 4)分解,但是当我将它作为 1 运行时,我得到:
(1, 2) : True
(1, 0) : False
(1, 3) : True
(1, 1) : True
谁能帮我理解代码有什么问题?或者我可能不理解我所指的答案中发布的算法。
(注意:我可能完全错了,但我了解到 defaultdict 会创建条目,即使它不存在,如果条目存在,算法会将其变为真,也许这就是我不确定的问题,但它是我试图走的思路,但它对我不起作用,因为它似乎破坏了整体实施) 谢谢!
【问题讨论】:
标签: python algorithm dynamic-programming