【发布时间】:2014-10-02 07:00:03
【问题描述】:
我正在做一个动态编程算法,在整个晚上毫无希望地调试我的程序之后,我都没有答案了。基本上,当我使用缓存来存储中间结果时,我的程序会返回错误的答案。这是我的程序:
def cachecost(cache, i, j, seq1, seq2):
if cache[i][j] is None:
v1 = v2 = v3 = v4 = None
if i > 0 and j > 0:
v1 = cachecost(cache, i-1, j-1, seq1, seq2) + 5
if i > 0 and j >= 0:
v2 = cachecost(cache, i-1, j, seq1, seq2) + 1
if i >= 0 and j > 0:
v3 = cachecost(cache, i, j-1, seq1, seq2) + 1
if i == 0 and j == 0:
v4 = 0
cache[i][j] = max(v1, v2, v3, v4)
return cache[i][j]
def cost(cache, i, j, seq1, seq2):
v1 = v2 = v3 = v4 = None
if i > 0 and j > 0:
v1 = cost(cache, i-1, j-1, seq1, seq2) + 5
if i > 0 and j >= 0:
v2 = cost(cache, i-1, j, seq1, seq2) + 1
if i >= 0 and j > 0:
v3 = cost(cache, i, j-1, seq1, seq2) + 1
if i == 0 and j == 0:
v4 = 0
cache[i][j] = max(v1, v2, v3, v4)
return max(v1, v2, v3, v4)
def main():
seq1 = 'AATAAT'
seq2 = 'AAGG'
cache = [[None] * (len(seq2) + 1)] * (len(seq1) + 1)
cachescore = cachecost(cache, len(seq1), len(seq2), seq1, seq2)
score = cost(cache, len(seq1), len(seq2), seq1, seq2)
print 'Score without cache: %s, score with cache: %s' % (cachescore, score)
# Handle command line execution
if __name__ == '__main__':
main()
该算法基本上通过递归计算i * j 表,其中缓存实现确保表中的每个条目只计算一次。
运行程序会产生以下输出:
Score without cache: 36, score with cache: 22
我在这里做错了什么?
【问题讨论】:
标签: python recursion dynamic-programming