gpt4 book ai didi

python - 生成最优二叉搜索树 (Cormen)

转载 作者:太空狗 更新时间:2023-10-30 01:36:38 24 4
gpt4 key购买 nike

我正在阅读 Cormen 等人的算法导论(第 3 版)(PDF),关于最佳二叉搜索树的第 15.4 节,但是我在实现伪代码时遇到了一些麻烦optimal_bst Python 中的函数。

这是我尝试将最佳 BST 应用到的示例:

enter image description here

让我们定义e[i,j]作为搜索包含标记为 i 的键的最佳二叉搜索树的预期成本至 j .最终,我们希望计算 e[1, n] , 其中n是键的数量(本例中为 5)。最终的递归公式是:

enter image description here

应该通过以下伪代码实现:

enter image description here

请注意,伪代码可互换地使用基于 1 和 0 的索引,而 Python 仅使用后者。因此,我在实现伪代码时遇到了麻烦。这是我目前所拥有的:

import numpy as np

p = [0.15, 0.10, 0.05, 0.10, 0.20]
q = [0.05, 0.10, 0.05, 0.05, 0.05, 0.10]
n = len(p)

e = np.diag(q)
w = np.diag(q)
root = np.zeros((n, n))
for l in range(1, n+1):
for i in range(n-l+1):
j = i + l
e[i, j] = np.inf
w[i, j] = w[i, j-1] + p[j-1] + q[j]
for r in range(i, j+1):
t = e[i-1, r-1] + e[r, j] + w[i-1, j]
if t < e[i-1, j]:
e[i-1, j] = t
root[i-1, j] = r

print(w)
print(e)

但是,如果我运行这个权重 w得到正确计算,但预期搜索值 e保持“卡住”在它们的初始值:

[[ 0.05  0.3   0.45  0.55  0.7   1.  ]
[ 0. 0.1 0.25 0.35 0.5 0.8 ]
[ 0. 0. 0.05 0.15 0.3 0.6 ]
[ 0. 0. 0. 0.05 0.2 0.5 ]
[ 0. 0. 0. 0. 0.05 0.35]
[ 0. 0. 0. 0. 0. 0.1 ]]
[[ 0.05 inf inf inf inf inf]
[ 0. 0.1 inf inf inf inf]
[ 0. 0. 0.05 inf inf inf]
[ 0. 0. 0. 0.05 inf inf]
[ 0. 0. 0. 0. 0.05 inf]
[ 0. 0. 0. 0. 0. 0.1 ]]

我期望的是 e , w , 和 root如下:

enter image description here

到目前为止,我已经调试了几个小时,但仍然卡住了。有人可以指出上面的 Python 代码有什么问题吗?

最佳答案

在我看来,您在索引中犯了一个错误。我无法让它按预期工作,但下面的代码应该会告诉你我要去的地方(某处可能有一个偏离):

import numpy as np

p = [0.15, 0.10, 0.05, 0.10, 0.20]
q = [0.05, 0.10, 0.05, 0.05, 0.05, 0.10]
n = len(p)

def get2(m, i, j):
return m[i - 1, j - 1]


def set2(m, i, j, v):
m[i - 1, j - 1] = v


def get1(m, i):
return m[i - 1]


def set1(m, i, v):
m[i - 1] = v


e = np.diag(q)
w = np.diag(q)
root = np.zeros((n, n))
for l in range(1, n + 1):
for i in range(n - l + 2):
j = i + l - 1
set2(e, i, j, np.inf)
set2(w, i, j, get2(w, i, j - 1) + get1(p, j) + get1(q, j))
for r in range(i, j + 1):
t = get2(e, i, r - 1) + get2(e, r + 1, j) + get2(w, i, j)
if t < get2(e, i, j):
set2(e, i, j, t)
set2(root, i, j, r)

print(w)
print(e)

结果:

[[ 0.2   0.4   0.5   0.65  0.9   0.  ]
[ 0. 0.2 0.3 0.45 0.7 0. ]
[ 0. 0. 0.1 0.25 0.5 0. ]
[ 0. 0. 0. 0.15 0.4 0. ]
[ 0. 0. 0. 0. 0.25 0. ]
[ 0.5 0.7 0.8 0.95 0. 0.3 ]]
[[ 0.2 0.6 0.8 1.2 1.95 0. ]
[ 0. 0.2 0.4 0.8 1.35 0. ]
[ 0. 0. 0.1 0.35 0.85 0. ]
[ 0. 0. 0. 0.15 0.55 0. ]
[ 0. 0. 0. 0. 0.25 0. ]
[ 0.7 1.2 1.5 2. 0. 0.3 ]]

关于python - 生成最优二叉搜索树 (Cormen),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46160969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com