[英]Python: counting number of items in dictionary with given value in O(logN)
I want to count the number of items in a dictionary with the given value (suppose the value in dictionary is just number), I've searched online and find two approaches, the first one : 我想用给定的值计算字典中的项目数(假设字典中的值只是数字),我在线搜索了两种方法, 第一种 :
sum(x == chosen_value for x in d.values())
the second approach is using Counter in Collections module. 第二种方法是使用“ 集合中的 计数器”模块。
However, I think the running time of both approaches is O(N)
, where N
is the total number of items in the dictionary. 但是,我认为这两种方法的运行时间都是
O(N)
,其中N
是字典中项的总数。 I want to find out a way to do this in O(logN)
, is it possible? 我想在
O(logN)
找到一种方法来执行此操作,这可能吗?
Thanks in advance for any help and suggestion! 在此先感谢您的帮助和建议!
Update: 更新:
Thanks for all the quick reply! 感谢您的所有快速回复! It cannot be done in
O(logN)
. 不能在
O(logN)
。 I may use binary tree to store the (key,value) pairs instead. 我可能使用二叉树来存储(键,值)对。
No. Why would you expect it to be possible? 否。您为什么期望这是可能的? It might be if you had a binary search tree, but dicts are unordered, so you have to iterate through the values.
可能是如果您有一个二叉搜索树,但是字典是无序的,因此您必须遍历这些值。
You have to read every value in a given dictionary if you have no prior knowledge of these values, which is the normal case. 如果您不了解这些值,则必须阅读给定词典中的每个值,这是正常情况。 So in the usual case, it has to be
O(N)
. 因此,在通常情况下,它必须是
O(N)
。
You could maintain another dictionary which maps values to count. 您可以维护另一个字典,该字典映射要计数的值。 That would give you the counts that you seek in O(1).
这将为您提供您在O(1)中寻求的计数。 The idea would be to implement a higher order data structure that acts like a dictionary, but adds the capability to return counts for values by maintaining another dictionary internally.
这个想法是实现一个像字典一样的高阶数据结构,但是通过内部维护另一个字典来增加返回值计数的能力。
I realize that this is probably not what you are asking. 我意识到这可能不是您要的。 Just putting it out there, just on the off chance.
只需将其放到那里,就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.