加速使用itertools

2024-04-26 04:13:41 发布

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

我正在尝试解决hackerrank中的苹果和橘子问题。你知道吗

我想出了一个解决办法

s,t = raw_input().strip().split(' ')
s,t = [int(s),int(t)]
a,b = raw_input().strip().split(' ')
a,b = [int(a),int(b)]
m,n = raw_input().strip().split(' ')
m,n = [int(m),int(n)]
apple = map(int,raw_input().strip().split(' '))
orange = map(int,raw_input().strip().split(' '))

ap=0
for e in apple:
    d=a+e
    if d>=s and d<=t:
        ap+=1
ora=0
for e in orange:
    d=b+e
    if d>=s and d<=t:
        ora+=1

print ('%d\n%d' %(ap,ora))

我想加快速度。所以我在google上搜索了一种同时迭代两个列表的方法,并使用了itertools,这就是我提出的解决方案

s,t = raw_input().strip().split(' ')
s,t = [int(s),int(t)]
a,b = raw_input().strip().split(' ')
a,b = [int(a),int(b)]
m,n = raw_input().strip().split(' ')
m,n = [int(m),int(n)]
apple = map(int,raw_input().strip().split(' '))
orange = map(int,raw_input().strip().split(' '))

ap=ora=0
for i,j in itertools.izip_longest(apple,orange):
    if i is not None:
        d1=a+i
        if d1>=s and d1<=t:
            ap+=1

    if j is not None:
        d2=b+j
        if d2>=s and d2<=t:
            ora+=1

print ('%d\n%d' %(ap,ora))

这真的能让代码在理论上更快吗?你知道吗


Tags: andinmapappleforinputrawif
1条回答
网友
1楼 · 发布于 2024-04-26 04:13:41

可能不会。你知道吗

您引入了两个额外的分支,每次循环运行时都必须对这些分支进行测试

if i is not None:

if j is not None:

以及创建生成器对象和解包元组的开销。我在这里看到的唯一可能的好处可能是减少了需要执行的循环边界检查的数量,但是您必须对其进行基准测试,以确定这是否超过了这两个if条件。这也只有在两个列表长度相似的情况下才有机会帮助你。你知道吗

相关问题 更多 >