繁体   English   中英

如何使Leetcode上的Python代码更快?

[英]How can I make my Python code on Leetcode more faster?

问题:给定一个数字num数组,其中两个元素恰好出现一次,所有其他元素恰好出现两次。 查找仅出现一次的两个元素。 例:

Input:  [1,2,1,3,2,5]
Output: [3,5]

那是我的代码:

class Solution:
    def singleNumber(self, nums):

        single=set(nums)
        my_list_tek=list(single)
        z=[a for a in nums if not a in my_list_tek or my_list_tek.remove(a)]
        return [i for i in nums if not i in z]

Counter与列表理解一起使用可以加快速度:

from collections import Counter
d = Counter([1,2,1,3,2,5])
[k for k,v in d.items() if v==1]

[3, 5]
from collections import Counter

class Solution:
    def singleNumber(self, nums):
        single=set(nums)
        my_list_tek=list(single)
        z=[a for a in nums if not a in my_list_tek or my_list_tek.remove(a)]
        return [i for i in nums if not i in z]

def test1(data):
    return [x for x in range(len(data)) if data[x] not in data[:x] + data[x + 1:]]

def test2(data):
    return Solution().singleNumber(data)

def test3(data):
    d = Counter(data)
    return [k for k, v in d.items() if v == 1]

让我们看看他们的表现如何:

>>> in_data = [1,2,1,3,2,5]
>>> timeit.timeit("test1(in_data)", setup="from __main__ import test1, in_data", number=100000)
0.2761846099997456
>>> timeit.timeit("test2(in_data)", setup="from __main__ import test2, in_data", number=100000)
0.2404884940001466
>>> timeit.timeit("test3(in_data)", setup="from __main__ import test3, in_data", number=100000)
0.45264831800022876

嗯,看来您毕竟不会太慢,而Counter方法太糟糕了。 让我们尝试更多的数据(也许使用Counter会赶上来)。

>>> in_data = [6, 93, 66, 34, 79, 3, 56, 92, 75, 6, 35, 2, 2, 59, 94, 61, 29, 97, 99, 58, 42, 99, 74, 94, 93, 98, 76, 73, 78, 42, 60, 68, 58, 70, 36, 16, 11, 43, 16, 47, 5, 79, 66, 28, 89, 41, 50, 16, 81, 23, 45, 4, 19, 91, 51, 33, 22, 24, 77, 42, 64, 20, 76, 71, 38, 5, 45, 14, 85, 93, 28, 11, 47, 89, 83, 85, 12, 89, 74, 29, 57, 51, 74, 84, 86, 84, 63, 86, 60, 68, 31, 35, 60, 53, 72, 49, 80, 69, 66, 44]
>>> timeit.timeit("test1(in_data)", setup="from __main__ import test1, in_data", number=10000)
2.0650007710000864
>>> timeit.timeit("test2(in_data)", setup="from __main__ import test2, in_data", number=10000)
0.9076229890001741
>>> timeit.timeit("test3(in_data)", setup="from __main__ import test3, in_data", number=10000)
0.14566440800035707

为什么会这样,的确如此。

dta = [1,2,1,3,2,5]
ctr = Counter(dta).most_common()
least2, least1 = ctr.pop(), ctr.pop()
print(least1[0], least2[0])

尽管有用的集合和itertools都是抽象的,但是当您具有特定领域的知识时,我发现它们没有比自己动手做的更好的了。

暂无
暂无

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

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