【发布时间】:2020-08-09 06:04:58
【问题描述】:
我想确定用于解决 Python 中的背包问题的动态编程算法的运行时间。我知道 import timeit 和 time 但不知道如何在这里实现它们。我不是一个很好的程序员!
def DPKP(v, s, C):
# Applies the dynamic programming method to the knapsack problem where v are the
# values of the n items, s are the sizes of the n items, and C is the capacity.
n = len(v)
V = [ [0 for cp in range(C+1)] for j in range (n) ]
X = [ [0 for cp in range(C+1)] for j in range (n) ]
for cp in range(C+1):
if s[n-1] <= cp:
V[n-1][cp] = v[n-1]
X[n-1][cp] = 1
for i in reversed(range(n-1)):
for cp in range(C+1):
if s[i] <= cp:
if v[i] + V[i+1][cp-s[i]] > V[i+1][cp]:
V[i][cp] = v[i] + V[i+1][cp-s[i]]
X[i][cp] = 1
else:
V[i][cp] = V[i+1][cp]
else:
V[i][cp] = V[i+1][cp]
return V, X
【问题讨论】:
-
"我知道 import timeit 和 time 但不知道如何在这里实现它们。"你读过文档吗?
标签: python python-3.x algorithm time