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

时间:2018-11-06 21:02:10

标签: python performance

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

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]

3 个答案:

答案 0 :(得分:1)

结合列表理解功能使用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]

答案 1 :(得分:0)

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

为什么会这样呢?

答案 2 :(得分:0)

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

尽管有用的集合和itertools是抽象的,但是当您具有特定领域的知识时,我发现它们并没有比“随您动”更好。