【发布时间】:2014-09-02 04:14:26
【问题描述】:
我是编程的初学者,并开始使用 Python 作为学习它的一种手段。我目前正在研究一组使用 for 循环 () 和 while 循环 () 的行。 目前我有这个:
def missingDoor(trapdoor,roomwidth,roomheight,step):
safezone = []
hazardflr = givenSteps(roomwidth,step,True)
safetiles = []
for i,m in enumerate(hazardflr):
safetiles.append((m,step))
while i < len(safetiles):
nextSafe = safetiles[i]
if knownSafe(roomwidth, roomheight, nextSafe[0], nextSafe[1]):
if trapdoor[nextSafe[0]/roomwidth][nextSafe[0]%roomwidth] is "0":
if nextSafe[0] not in safezone:
safezone.append(nextSafe[0])
for e in givenSteps(roomwidth,nextSafe[0],True):
if knownSafe(roomwidth, roomheight, e, nextSafe[0]):
if trapdoor[e/roomwidth][e%roomwidth] is "0" and (e,nextSafe[0]) not in safetiles:
safetiles.append((e,nextSafe[0]))
i += 1
return sorted(safezone)
然后在社区成员的帮助下,我能够更有效地将公共变量 nextSafe[0] 设置为 ns 并从顶部调用它:
def missingDoor(trapdoor,roomwidth,roomheight,step):
safezone = []
hazardflr = givenSteps(roomwidth,step,True)
safetiles = []
for i,m in enumerate(hazardflr):
safetiles.append((m,step))
while i < len(safetiles):
nextSafe = safetiles[i]
ns0 = nextSafe[0]
if knownSafe(roomwidth, roomheight, ns0, nextSafe[1]):
if trapdoor[ns0/roomwidth][ns0 % roomwidth] is "0":
if ns0 not in safezone:
safezone.append(ns0)
for e in givenSteps(roomwidth,ns0,True):
if knownSafe(roomwidth, roomheight, e, ns0):
if trapdoor[e/roomwidth][e%roomwidth] is "0" and (e, ns0) not in safetiles:
safetiles.append((e, ns0))
i += 1
return sorted(safezone)
这些都取代了价值效率,但有没有其他方法可以提高效率并可能节省线路? knownSafe(), givenSteps() 函数来自另一个代码,该代码与此代码一起查找可能的安全区和已知步骤。但我的问题是如何使这段代码更高效,因为最初我开始使用 while loops() 并发现在给定已知列表时 for 循环更好。考虑到我是编程新手,一直在尝试各种事情。
提前谢谢你!!
【问题讨论】:
-
请确保您的示例中的缩进是正确的。至少
for语句之后的行处于错误的缩进级别。 -
你能描述一下你的算法吗?
-
如果此代码有效(您有测试输入和输出来检查吗?)考虑将问题移至codereview.stackexchange.com。另外,请考虑您所说的效率是什么意思 - 内存使用、处理速度、可读性……
标签: python python-2.7 if-statement for-loop while-loop