【问题标题】:how to find the element in a list having most occurrence using loop如何使用循环查找列表中出现次数最多的元素
【发布时间】:2017-03-14 02:31:58
【问题描述】:

假设

[1,2,4,4,3,3,3]

且upper_limit为8(所有数字均不大于upper_limit)

如何在upper_limit的帮助下产生3 必须在 O(n+upper_limit) 总时间内运行。

【问题讨论】:

标签: python-3.x loops big-o


【解决方案1】:
a = [1,1,2,2,2,3,3,4]
cnt = {}
most = a[0]
for x in a:
    if x not in cnt:
        cnt[x] = 0
    cnt[x] += 1
    if cnt[x] > cnt[most]:
        most = x

print(most)

【讨论】:

  • {}是什么意思
  • @Lindadadad 这意味着定义一个空的字典名称cnt。字典中的项目有一个键和一个值。使用前需要先添加密钥。
【解决方案2】:

您可以使用collections.Counter

from collections import Counter

lst = [1,2,4,4,3,3,3]
counter = Counter(lst)
most_freq, freq = counter.most_common()[0]

使用字典替代Counter

from collections import defaultdict

d = defaultdict(int)
lst = [1,2,4,4,3,3,3]

for val in lst:
    d[val] = d[val] + 1

most_freq, freq = max(d.items(), key = lambda t: t[1])

此示例会在您通过规避max 函数的需要进行迭代时跟踪最频繁的情况。

from collections import defaultdict

d = defaultdict(int)
lst = [1,2,4,4,3,3,3]
most_freq, freq = None, 0

for val in lst:
    d[val] = d[val] + 1
    if d[val] > freq:
        most_freq = val
        freq = d[val]

print(most_freq, freq)

如果您不想使用defaultdict,那么您可以使用普通字典并改用dict.setdefault

d = {} # set d to dict
d[val] = d.setdefault(val, 0) + 1

【讨论】:

  • 你认为这是 O(n) 吗?因为我在文档中看不到任何表明这一点的内容。
  • 是的,顺便说一句,你知道如何使用while循环和for循环编码吗?
  • 你可以使用字典来实现类似的事情,这将是O(n + len(dict)) Counter 比字典更快,但我相信它大致相同。
  • @Lindadadad 是的,我知道如何使用 for 循环和 while 循环。怎么样?
  • 你能告诉我如何用循环编码吗?我见过很多使用 collections.counter 的方法,除了循环!谢谢
猜你喜欢
  • 2020-07-22
  • 2011-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多