python - 我的嵌套 For 循环比内联 For 循环运行“更快”
问题描述
对于我所在的课程,我们被要求写出一个蛮力方法,用于在列表S1、S2中查找 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
为什么会这样?我的印象是内联语法本质上只是写出嵌套循环的语法糖,但显然有些不同,我不知道是什么。
解决方案
循环确实是相等的,但不是打破它的条件。在第一个嵌套循环中,代码在达到第一个相等时停止。在第二个中,计算所有测试,直到用尽所有组合。
具有理解语法的第一个循环的等价物是使用生成器 and any
,当达到第一个真值时它将停止
return any((a+b==x for a in s2 for b in s1))
推荐阅读
- php - 我可以使用 API 在移动设备中使用服务器端支付集成吗
- php - 数据表未显示来自查询的所有数据
- javascript - 切换表格的显示:不是第一列
- java - 如何在数组中打印 [ ] (Java)
- visual-studio - 使用 Visual Studio 2017 Docker build 未将 site.css 样式应用于 Docker 映像
- c# - 将 C# 流式接口转换为 VB.NET 中的代码
- amazon-web-services - 使用 AWS cognito 将自己的 api 作为第三方
- javascript - 将 data-dismiss="modal" 绑定到键单击
- c# - 当值不是数字时,自定义数字验证无法正常工作
- vue.js - Vue JS 许多相同的选择下拉菜单使用 v-model