PYTHON中的for-loop-while-loop效率

2024-09-22 16:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程初学者,并开始使用Python作为学习它的方法。我目前正在研究一组用于循环()和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,并从顶部调用它:

^{pr2}$

这些都取代了价值效率,但有没有其他方法可以让这种效率更高,并可能节省线路?knownSafe(),givenSteps()函数来自另一个使用此代码的代码来查找可能的安全区域和knownsteps。但我的问题是如何使这段代码更有效率,因为最初我开始使用while loops()并发现在给定已知列表时for循环更好。我一直在尝试各种各样的事情,因为我对编程还不熟悉。在

提前谢谢你!!在


Tags: 代码inforifstepappendwhileroomwidth
1条回答
网友
1楼 · 发布于 2024-09-22 16:34:27

所以。。你想要代码复查吗?Here..

不管怎样,我会尽力帮助你的。

代码

def missingDoor(trapdoor, roomwidth, roomheight, step):
    safezone, safetiles = [], []
    check = lambda a, b, c, l: knownSafe(roomwidth, roomheight, a, b) and trapdoor[a/roomwidth][a%roomwidth] == '0' and c not in l

    for i, m in enumerate(givenSteps(roomwidth, step, True)):
        safetiles.append((m, step))
        for _ in range(i, len(safetiles)):
            nextSafe = safetiles[i]
            ns0 = nextSafe[0]

            if check(ns0, nextSafe[1], ns0, safezone):
                safezone.append(ns0)
                safetiles.extend([ (e, ns0) for e in givenSteps(roomwidth,ns0,True) if check(e, ns0, (e, ns0), safetiles) ])
    return sorted(safezone)

说明

Line 1: function definition
Line 2: declaring the variables, this condensed style of declaring more than one variable on a line has nothing to do with efficiency, It's just a matter of style
Line 3: That's an important approach, because it shows how Functional Programming(one of the programming paradigms supported by python) can help in code clarity (again, no memory efficiency, just code efficiency, which will help in the long run) .. the lambda in a nutshell, is simply a condensed function that contains only one line of code, and returns it back, so no need for the return statement here, actually, there's more to the lambda than that, but that's basically why you'd like to implement one in a situation like that .. The goal of this specific one here, is to check the variables using the repeated check you ran every few lines I couldn't help but notice how messy it was! So this function exists to simply organize that .. The first and second parameters are self-explanatory, the third parameter is the one to check for its existence in the fourth parameter (which I suppose is a list) ..
Line 5: The loop start, nothing strange, except that I used the function's return value directly into the loop, because I thought storing it as a variable and using it only once would be a waste of RAM ..
Line 6: Unchanged ..
Line 7: I changed the while loop to a for loop, because I noticed the sole reason you used a while loop instead of a for loop is that the value of i changed every time the outer loop ran, so, why not provide a range ? That'd be more code and memory efficient
Line 8, 9: Unchanged ..
Line 11: We used the lambda, tadaaa ! Same call like a function ..
Line 12: Unchanged ..
Line 13: That technique here is called List Comprehension, that's a little bit advanced, but, in a nutshell, it creates a list that just gets the left-most value appended to each time the loop inside ran, any other conditions on the right are executed every time the loop ran, if returns true, the left-most value is appended, else, the loop continues over .. The list returned from all that, gets added to the safetiles list, note that: the extend method of a list simply appends all the elements in the argument list to the caller list, in this case: each of the elements of the list returned as a result of the list comprehension, simply gets appended to safetiles .. This isn't really an overkill as it may seem, because it actually clarifies code, and uses even less memory ..
Line 14: returns the safetiles list .. Mission Accomplished!

希望这有帮助;) 注意,使用“is'0”进行检查不是一个好的做法,更好的做法是:“=='0'”

相关问题 更多 >