Skip to content Skip to sidebar Skip to footer

Python Orderedset With .index() Method

Does anyone know about a fast OrderedSet implementation for python that: remembers insertion order has an index() method (like the one lists offer) All implementations I found ar

Solution 1:

You can always add it in a subclass. Here is a basic implementation for the OrderedSet you linked in a comment:

classIndexOrderedSet(OrderedSet):
    defindex(self, elem):
        if key in self.map:
            returnnext(i for i, e inenumerate(self) if e == elem)
        else:
            raise KeyError("That element isn't in the set")

You mentioned you only need add, index, and in-order iteration. You can get this by using an OrderedDict as storage. As a bonus, you can subclass the collections.Set abstract class to get the other set operations frozensets support:

from itertools import count, izip
from collections import OrderedDict, SetclassIndexOrderedSet(Set):
    """An OrderedFrozenSet-like object
       Allows constant time 'index'ing
       But doesn't allow you to remove elements"""def__init__(self, iterable = ()):
        self.num = count()
        self.dict = OrderedDict(izip(iterable, self.num))
    defadd(self, elem):
        if elem notin self:
            self.dict[elem] = next(self.num)
    defindex(self, elem):
        return self.dict[elem]
    def__contains__(self, elem):
        return elem in self.dictdef__len__(self):
        returnlen(self.dict)
    def__iter__(self):
        returniter(self.dict)
    def__repr__(self):
        return'IndexOrderedSet({})'.format(self.dict.keys())

You can't subclass collections.MutableSet because you can't support removing elements from the set and keep the indexes correct.

Post a Comment for "Python Orderedset With .index() Method"