【问题标题】:Count occurence in a list with time complexity of O(nlogn)计算时间复杂度为 O(nlogn) 的列表中的出现次数
【发布时间】:2013-12-15 06:21:00
【问题描述】:

这是我目前所拥有的:

alist=[1,1,1,2,2,3,4,2,2,3,2,2,1]
def icount(alist):
    adic={}
    for i in alist:
        adic[i]=alist.count(i)
    return adic

print(icount(alist))

我做了一些研究,发现 list.count() 的时间复杂度是 O(n),因此,这段代码将是 O(n^2)。

有没有办法将其减少到 O(nlogn)?

【问题讨论】:

  • collections.Counter。它就是为这类工作而存在的。
  • 如果只增加adic[i],复杂度应该是O(n)。
  • 但是我怎么知道它的时间复杂度呢?

标签: python list python-3.x


【解决方案1】:

你可以像这样使用Counter

from collections import Counter
alist=[1,1,1,2,2,3,4,2,2,3,2,2,1]
print Counter(alist)

如果你想使用你的解决方案,你可以像这样改进它

def icount(alist):
    adic = {}
    for i in alist:
        adic[i] = adic.get(i, 0) + 1
    return adic

更好的是,你可以像这样使用defaultdict

from collections import defaultdict
adic = defaultdict(int)
for i in alist:
    adic[i] += 1
return adic

另外,你可能想看看不同 Python 对象上各种操作的时间复杂度here

【讨论】:

  • get 是列表数据类型的函数吗? alist.get(2,0) 给我一个错误
  • @AswinMurugesh 对不起。解决它。请立即检查:)
  • 你能解释一下它到底是做什么的吗?
  • @AswinMurugesh 它将尝试获取dict中第一个参数的值,如果它不存在,它只是返回第二个参数。
  • 所以,如果我是对的,这是if i in adic: adic[i] += 1 else: adic[i] = 1 的较短版本吗??
【解决方案2】:

计数器是你的帮手:

>>> from collections import Counter
>>> a = [1,2,1,3,4]
>>>  Counter(a)
Counter({1: 2, 2: 1, 3: 1, 4: 1})
>>> x = Counter(a)     
>>> x[1]
2
>>> x[2]
1

通过此方法轻松获取每个元素的计数

【讨论】:

    猜你喜欢
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多