Search code examples
pythonpython-2.7python-itertools

Speeding up using itertools


I am trying to solve the Apple and Orange problem in hackerrank.

Here is one solution I came up with

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))

I wanted to speed this up. So I googled for a way to iterate both lists at the same time and so used itertools and this is the solution I came up with

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))

Does this really make the code faster theoretically?


Solution

  • Probably not.

    You have introduced two additional branches that must be tested each time the loop runs

    if i is not None:
    
    if j is not None:
    

    as well as the overhead of creating the generator object and unpacking the tuple. The only possible benefit I see here is possibly reducing the amount of loop boundary checks that need to be done but you will have to benchmark it to see if that outweighs the two if conditions. That also only has a chance of helping you if the two lists are similar in length.