Python - 动态编程不会提高速度
Python - Dynamic programing doesn't improve speed
我想为 Minesweepers/Cheess 创建 N 维板,但当我使用 DP 来提高速度时,我 运行 遇到了问题,但是两个版本之间的速度似乎相同.
版本 1:朴素递归
def createboard_nd(dimensions, value=None):
if len(dimensions) == 1:
return [value for _ in range(dimensions[0])]
else:
return [createboard_nd(dimensions[1:], value) for _ in range(dimensions[0])]
版本 2:带 DP 的递归
def createboard_nd(dimensions, value=None, memo=None):
if memo is None:
memo = {}
if len(dimensions) in memo:
return memo[len(dimensions)]
if len(dimensions) == 1:
memo[len(dimensions)] = [value for _ in range(dimensions[0])]
return memo[len(dimensions)]
else:
memo[len(dimensions)] = [createboard_nd(dimensions[1:],value, memo) for _ in range(dimensions[0])]
return memo[len(dimensions)]
例子
createboard_nd((10,10,10,10,10,10), 1)
似乎 jupyternotebook 内置时间计数有错误或其他问题,在 运行 脚本版本 2 之后似乎快得多。
我想为 Minesweepers/Cheess 创建 N 维板,但当我使用 DP 来提高速度时,我 运行 遇到了问题,但是两个版本之间的速度似乎相同.
版本 1:朴素递归
def createboard_nd(dimensions, value=None):
if len(dimensions) == 1:
return [value for _ in range(dimensions[0])]
else:
return [createboard_nd(dimensions[1:], value) for _ in range(dimensions[0])]
版本 2:带 DP 的递归
def createboard_nd(dimensions, value=None, memo=None):
if memo is None:
memo = {}
if len(dimensions) in memo:
return memo[len(dimensions)]
if len(dimensions) == 1:
memo[len(dimensions)] = [value for _ in range(dimensions[0])]
return memo[len(dimensions)]
else:
memo[len(dimensions)] = [createboard_nd(dimensions[1:],value, memo) for _ in range(dimensions[0])]
return memo[len(dimensions)]
例子
createboard_nd((10,10,10,10,10,10), 1)
似乎 jupyternotebook 内置时间计数有错误或其他问题,在 运行 脚本版本 2 之后似乎快得多。