简体   繁体   English

使Python代码更快

[英]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. 代码必须根据de列表中是否存在c列表的元素来增加或减少happy变量。 This code runs fine for small number of elements in c , d and e lists. 对于cde列表中的少量元素,此代码运行良好。 But when there are many elements , the code execution is terminated due to timeout. 但是,当元素很多时,由于超时而终止了代码执行。

What can I do to make it run faster? 我该怎么做才能使其运行更快?

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 . 变量happy本质上是d中找到的元素数与e找到的元素数之差。

Could there be duplicates in c ? c是否可以有重复项?

If you want to count the same element only once, then you can use set , that implicitly remove duplicates: 如果只想对同一元素计数一次,则可以使用set ,它隐式删除重复项:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM