在Python中使用回忆进行网格传播器
我正在尝试解决问题:
MXN网格上有一个机器人。该机器人最初位于左上角(即网格[0] [0])。机器人试图移至右下角(即网格[M -1] [n -1])。机器人只能在任何时间点向下移动或向右移动。 鉴于两个整数M和N,请返回机器人到达右下角的可能所需的独特路径的数量。 我已经成功地为其创建了代码,并且正在优化代码以更快运行的过程。
我的第一个方法是:
gridTraveler_memo = {}
def gridTraveler(m,n):
if (m and n) not in gridTraveler_memo:
if m==1 and n==1:
return 1
elif m==0 or n==0:
return 0
else:
gridTraveler_memo[m,n] = gridTraveler(m-1,n) + gridTraveler(m,n-1)
return gridTraveler_memo[m,n]
print(gridTraveler(18,18))
我的第二种方法是使用functools.cache(uisng 在这里):
import functools
@functools.cache
def gridTraveler(m,n):
if m==1 and n==1:
return 1
elif m==0 or n==0:
return 0
else:
return gridTraveler(m-1,n) + gridTraveler(m,n-1)
print(gridTraveler(18,18))
我的第二组代码的工作速度要比我的第一组代码快得多。但是,我不完全理解“ functools.cache”功能,因为我是Python的新手。
在我有限的专业知识中,看来第一盘代码更像是对未来的好典范。例如,在大型项目上工作时,使用“ functools.cache”表示您正在使用更多内存。我是否正确地假设
I am trying to code with problem:
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.
Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
I have successfully created the code for it and I am in the process of optimizing the code to run faster.
My first method is:
gridTraveler_memo = {}
def gridTraveler(m,n):
if (m and n) not in gridTraveler_memo:
if m==1 and n==1:
return 1
elif m==0 or n==0:
return 0
else:
gridTraveler_memo[m,n] = gridTraveler(m-1,n) + gridTraveler(m,n-1)
return gridTraveler_memo[m,n]
print(gridTraveler(18,18))
My second method is using functools.cache (uisng the answer for here):
import functools
@functools.cache
def gridTraveler(m,n):
if m==1 and n==1:
return 1
elif m==0 or n==0:
return 0
else:
return gridTraveler(m-1,n) + gridTraveler(m,n-1)
print(gridTraveler(18,18))
My second set of code works a lot faster than my first set of code. However i don't fully understand "functools.cache" function, as i am new to python.
In my limited expertise, it seems that the first set code is more of a good pratice for the future. For example when working on a big project, using "functools.cache" means you are using more memory. Am i correct in assuming that
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论