Python set with the ability to pop a random element

前端 未结 6 1135
时光说笑
时光说笑 2020-12-30 23:43

I am in need of a Python (2.7) object that functions like a set (fast insertion, deletion, and membership checking) but has the ability to return a random value. Previous qu

6条回答
  •  爱一瞬间的悲伤
    2020-12-31 00:37

    One approach you could take is to derive a new class from set which salts itself with random objects of a type derived from int.

    You can then use pop to select a random element, and if it is not of the salt type, reinsert and return it, but if it is of the salt type, insert a new, randomly-generated salt object (and pop to select a new object).

    This will tend to alter the order in which objects are selected. On average, the number of attempts will depend on the proportion of salting elements, i.e. amortised O(k) performance.

提交回复
热议问题