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?
-
1You could use sets instead of listskhelwood– khelwood2017年07月05日 08:53:39 +00:00Commented 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.alec_djinn– alec_djinn2017年07月05日 09:29:52 +00:00Commented Jul 5, 2017 at 9:29
1 Answer 1
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)
1 Comment
d and e directly to intersection.