Misha
Misha

Reputation: 377

Make Python code faster

Is it possible to make this code run faster?

a,b=map(int,input().split())
c=list(map(int,input().split()))
d=list(map(int,input().split()))
e=list(map(int,input().split()))

happy=0

for i in c:
    if i in d:
        happy=happy+1
    elif i in e:
        happy=happy-1

print(happy)

The code has to increment or decrement happy variable depending on if elements of c list are present in d or e lists. This code runs fine for small number of elements in c, d and e lists. But when there are many elements , the code execution is terminated due to timeout.

What can I do to make it run faster?

Upvotes: 0

Views: 171

Answers (1)

FLab
FLab

Reputation: 7506

You can avoid the loop. The variable happy is essentially the difference between the number of elements found in d and the number of elements found in e.

Could there be duplicates in c?

If you want to count the same element only once, then you can use set, that implicitly remove duplicates:

set_c = set(c)
happy_match = set_c.intersect(d)
unhappy_match = set_c.intersect(e)

happy = len(happy) - len(unhappy_match)

If you want to count each occurrence (including duplicates), then you can apply the same logic to lists:

happy_match = sum(1 if el in d else 0 for el in c)
unhappy_match = sum(1 if el in e else 0 for el in c)

happy = len(happy) - len(unhappy_match)

Upvotes: 4

Related Questions