首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用枚举或其他函数时的循环效率

使用枚举或其他函数时的循环效率
EN

Stack Overflow用户
提问于 2014-07-11 05:02:36
回答 1查看 318关注 0票数 0

有人建议替换我的:

代码语言:javascript
复制
for m in hazardflr:
    safetiles.append((m, step))
    i = 0

采取更合理的办法,例如:

代码语言:javascript
复制
for i, m in enumerate(hazardflr):
    safetiles.append((m, step))

如果有更有效的方法,

我现在明白了这是如何节省代码行和说同样的话。我不知道enum()函数。我现在的问题是,是否还有其他的修改可以使这段代码更高效、更节省行?

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-11 05:23:15

nextSafe[0]分配给局部变量

使用表达式nextSafe[0]的代码是9次(如果我计算正确的话)。

从列表中访问项比从变量中选择值更昂贵。

修改如下:

代码语言:javascript
复制
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))

能让它加速一点。

safezone转换为set

一个测试item in list_var正在扫描整个列表,以确定list_var是一个列表。

如果将测试转到item in set_var,它几乎会立即知道结果,而不管set_var变量的大小如何,因为set有某种哈希,用作查找的“数据库索引”。

在代码中将safezone = []转换为safezone = set()

实际上,在您的情况下,您可以完全跳过成员资格测试:

代码语言:javascript
复制
if ns0 not in safezone:
    safezone.append(ns0)

可转化为:

代码语言:javascript
复制
safezone.add(ns0)

如集将负责只保留唯一的项目。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24690394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档