vendredi 3 avril 2020

Performance difference with if-statements

I was doing some Hackerrank problems in python 3, and a very simple solution for a problem was executing too long to be accepted as correct answer. The code for this solution is:

import collections
import sys

t = int(input())
for i in range(t):
    n = int(input())
    l = collections.deque(map(int, input().split()))
    last = sys.maxsize
    a = 'Yes'

    while len(l) > 0:
        l0 = l[0]
        l1 = l[-1]
        if l0 >= l1:
            if l0 <= last:
                last = l.popleft()
        elif l1 <= last:
            last = l.pop()
        else:
            a = 'No'
            break
    print(a)

I did a minor change and code was accepted, after a solution found on github. The changed code is:

import collections
import sys

t = int(input())
for i in range(t):
    n = int(input())
    l = collections.deque(map(int, input().split()))
    last = sys.maxsize
    a = 'Yes'

    while len(l) > 0:
        l0 = l[0]
        l1 = l[-1]
        if l0 >= l1:
            it = l.popleft()
        else:
            it = l.pop()
        if it > last:
            a = 'No'
            break
        else:
            last = it
    print(a)

The difference is one if-statement less, but a new variable is added. My question is if this one if-clause is slowing down the code "so much"? The parts in question are the if-statements inside the while loop. On my computer the first one executes slightly faster, but for the few shorter strings I was providing (about 10 elements max). Hackerrank's test was around 10 000 elements.

Aucun commentaire:

Enregistrer un commentaire