好吧,我正在寻找方法来优化我写的一个函数,作为这个问题的答案在python:
"给定一个整数方阵,每行包含到达起点所需的时间,第一人称,第二人称,…,最后一个人,并按此顺序出口。行顺序遵循相同的模式(开始,每个人,退出)。接人是即时的,可以重新访问不同的地点,移动到出口并不意味着你必须立即离开-如果时间允许,可以从出口来回移动以接更多的人。有些路径将时间添加回时钟。在时钟上添加时间将延迟出口门的关闭,如果在门已经关闭后时间回到0或正数,则触发出口重新打开。因此,绕圈行走并不断获得时间是可能的:也就是说,每次遍历一条路径时,使用或添加的时间是相同的。
目标是写一个函数来计算一个人可以接的最多人以及他们是哪些人,同时在门关闭之前仍然从出口逃离。该函数应该返回按排序顺序保存的人员的索引。"
我写的函数是:
def answer(times,time_limit):
mindic=min(min(times))
n=len(times)
def find_path(times, start, end,time, path=[]):
if start != 0 and start != end :
if start-1 in path:
pass
else:
path = path + [start-1]
if start == end and time-min(times[start][0:len(times[start])-1]) < mindic:
return path
best=None
for i in range(n):
if time-times[start][i] >= mindic and times[start][i] != 0 :
newpath = find_path(times, i, end,time-times[start][i], path)
if newpath != None :
if not best or len(newpath) > len(best):
best=newpath
return best
res=find_path(times,0,n-1,time_limit)
return res
调用函数将像这样:
answer([[0, 1, 1, 1, 1], [1, 0, 1, 1, 1], [1, 1, 0, 1, 1], [1, 1, 1, 0, 1], [1, 1, 1, 1, 0]],3)
,上面例子的答案是:
[0, 1]
只能保存索引为0和1的人。
使用'%% timeit 10'运行函数会得到以下结果:
1000 loops, best of 3: 180 µs per loop
有什么方法可以缩短时间吗?
EDIT:谢谢@quantummind,让它从221µs缩短到180µs。
EDIT2: @user2357112:我相信我已经解决了这个问题?现在,它不会拒绝访问同一位置两次的路径。
我不想完全理解你的代码,但如果你改变这些行,它可能会有所帮助
if start != 0 and start != end :
path = path + [start-1]
if len(path) != len(set(path)):
return
:
if start != 0 and start != end :
if start-1 in path:
return
path = path + [start-1]