python如何提高性能_Python-如何提高这段代码的性能?

在代码底部运行的示例需要很长时间才能在我的机器上解决:

dumrat@dumrat:~/programming/python$ time python camels.py

[['F', 'F', 'F', 'G', 'B', 'B', 'B'], ['F', 'F', 'G', 'F', 'B', 'B', 'B'],

['F', 'F', 'B', 'F', 'G', 'B', 'B'], ['F', 'F', 'B', 'F', 'B', 'G', 'B'],

['F', 'F', 'B', 'G', 'B', 'F', 'B'], ['F', 'G', 'B', 'F', 'B', 'F', 'B'],

['G', 'F', 'B', 'F', 'B', 'F', 'B'], ['B', 'F', 'G', 'F', 'B', 'F', 'B'],

['B', 'F', 'B', 'F', 'G', 'F', 'B'], ['B', 'F', 'B', 'F', 'B', 'F', 'G'],

['B', 'F', 'B', 'F', 'B', 'G', 'F'], ['B', 'F', 'B', 'G', 'B', 'F', 'F'],

['B', 'G', 'B', 'F', 'B', 'F', 'F'], ['B', 'B', 'G', 'F', 'B', 'F', 'F'],

['B', 'B', 'B', 'F', 'G', 'F', 'F']]

real 0m20.883s

user 0m20.549s

sys 0m0.020s

这是代码:

import Queue

fCamel = 'F'

bCamel = 'B'

gap = 'G'

def solution(formation):

return len([i for i in formation[formation.index(fCamel) + 1:]

if i == bCamel]) == 0

def heuristic(formation):

fCamels, score = 0, 0

for i in formation:

if i == fCamel:

fCamels += 1;

elif i == bCamel:

score += fCamels;

else:

pass

return score

def getneighbors (formation):

igap = formation.index(gap)

res = []

# AB_CD --> A_BCD | ABC_D | B_ACD | ABD_C

def genn(i,j):

temp = list(formation)

temp[i], temp[j] = temp[j], temp[i]

res.append(temp)

if(igap > 0):

genn(igap, igap-1)

if(igap > 1):

genn(igap, igap-2)

if igap < len(formation) - 1:

genn(igap, igap+1)

if igap < len(formation) - 2:

genn(igap, igap+2)

return res

class node:

def __init__(self, a, g, p):

self.arrangement = a

self.g = g

self.parent = p

def astar (formation, heuristicf, solutionf, genneighbors):

openlist = Queue.PriorityQueue()

openlist.put((heuristicf(formation), node(formation, 0, None)))

closedlist = []

while 1:

try:

f, current = openlist.get()

except IndexError:

current = None

if current is None:

print "No solution found"

return None;

if solutionf(current.arrangement):

path = []

cp = current

while cp != None:

path.append(cp.arrangement)

cp = cp.parent

path.reverse()

return path

#arr = current.arrangement

closedlist.append(current)

neighbors = genneighbors(current.arrangement)

for neighbor in neighbors:

if neighbor in closedlist:

pass

else:

openlist.put((current.g + heuristicf(neighbor),

node(neighbor, current.g + 1, current)))

#sorted(openlist, cmp = lambda x, y : x.f > y.f)

def solve(formation):

return astar(formation, heuristic, solution, getneighbors)

print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])

#print solve([fCamel, fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel, bCamel])

每只只供三只骆驼。我想至少这样做4次。该测试用例仍在运行(现在:()已经大约5分钟了。如果完成,我将对其进行更新。

我应该怎么做才能改善这段代码?(通常以性能为依据,但也欢迎其他建议)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值