首页 > 解决方案 > 我的嵌套 For 循环比内联 For 循环运行“更快”

问题描述

对于我所在的课程,我们被要求写出一个蛮力方法,用于在列表S1S2中查找 2 个元素,它们添加到指定的值x。到目前为止,我已经把它写出来了:

@timing
def brute_force_nested(x, s1 : list, s2 : list) -> bool:
    for a in s2:
        for b in s1:
            if a + b == x:
                return True
    return False

@timing
def brute_force_inline(x, s1 : list, s2 : list) -> bool:
    return bool([ (a,b) for a in s2 for b in s1 if a + b == x ])

但是当我在终端中运行它们时,我得到的时间差异很大:

>>> brute_force_nested(5123, S1, S2):

func:brute_force_nested took: 0.007085800170898438 sec and gave: True

>>>func:brute_force_inline(5123, S1, S2)

func:brute_force took: 3.0208868980407715 sec and gave: True

为什么会这样?我的印象是内联语法本质上只是写出嵌套循环的语法糖,但显然有些不同,我不知道是什么。

标签: pythonloopstime

解决方案


循环确实是相等的,但不是打破它的条件。在第一个嵌套循环中,代码在达到第一个相等时停止。在第二个中,计算所有测试,直到用尽所有组合。

具有理解语法的第一个循环的等价物是使用生成器 and any,当达到第一个真值时它将停止

return any((a+b==x for a in s2 for b in s1))

推荐阅读