我需要一个类似于集合的Python对象(2.7),能够快速插入、删除和检查成员资格,但具有返回随机值的能力。之前在stackoverflow上提出过类似问题的回答,例如:
import random
random.sample(mySet, 1)
但是对于大型集合来说,这种方法速度相当慢(它的时间复杂度为O(n))。
其他解决方案不够随机(它们依赖于Python集合的内部表示形式,会产生一些非常不随机的结果):
for e in mySet:
break
# e is now an element from mySet
我编写了自己的基本类,它具有常数时间的查找、删除和随机值特性。
class randomSet:
def __init__(self):
self.dict = {}
self.list = []
def add(self, item):
if item not in self.dict:
self.dict[item] = len(self.list)
self.list.append(item)
def addIterable(self, item):
for a in item:
self.add(a)
def delete(self, item):
if item in self.dict:
index = self.dict[item]
if index == len(self.list)-1:
del self.dict[self.list[index]]
del self.list[index]
else:
self.list[index] = self.list.pop()
self.dict[self.list[index]] = index
del self.dict[item]
def getRandom(self):
if self.list:
return self.list[random.randomint(0,len(self.list)-1)]
def popRandom(self):
if self.list:
index = random.randint(0,len(self.list)-1)
if index == len(self.list)-1:
del self.dict[self.list[index]]
return self.list.pop()
returnValue = self.list[index]
self.list[index] = self.list.pop()
self.dict[self.list[index]] = index
del self.dict[returnValue]
return returnValue
这段代码是否有更好的实现方式或者可以做出大幅度的改进?
foo.items()
、foo.keys()
(相当于list(foo)
)或foo.values()
更加简洁,而且每个方法都有一个“iter”版本可用于循环(生成迭代器而不是列表,因此速度稍快)(例如foo.iterkeys()
)。 - Izkata