0

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?

Matt
75.5k26 gold badges156 silver badges181 bronze badges
asked Jul 5, 2017 at 8:49
2
  • 1
    You could use sets instead of lists Commented Jul 5, 2017 at 8:53
  • There is no need to convert your inputs into integers. You can compare strings, the result will not change. Commented Jul 5, 2017 at 9:29

1 Answer 1

4

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)
answered Jul 5, 2017 at 9:00
Sign up to request clarification or add additional context in comments.

1 Comment

You can pass the lists d and e directly to intersection.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.