从时间复杂度为O(1)的集合中采样一个元素

时间:2019-04-08 11:47:36

标签: python set time-complexity sample

我在Python中有一个集合,我想从中取样一个元素,就像使用random.sample()方法一样。问题是sample()在内部将set转换为元组O(n),而我必须以最佳方式进行操作。

是否可以使用函数从时间复杂度为O(1)的集合中采样元素,或者唯一的方法是创建自己的set实现?

1 个答案:

答案 0 :(得分:1)

Because the data layout is irregular, it’s impossible to uniformly sample from a hash-based set in O(1) except, in the case of ω(n) queries, by preprocessing it into some sort of array. (Such an array could be maintained while building the set, of course, but that’s not the starting point given and isn’t faster to add than the tuple conversion.)