3
# Copyright (C) 2005 Canonical Ltd
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
# Author: Martin Pool <mbp@canonical.com>
22
class IntSet(Exception):
23
"""Faster set-like class storing only whole numbers.
25
Despite the name this stores long integers happily, but negative
26
values are not allowed.
28
>>> a = IntSet([0, 2, 5])
48
>>> a.update(range(5))
52
Being a set, duplicates are ignored:
62
# __slots__ = ['_val']
64
def __init__(self, values=None):
65
"""Create a new intset.
68
If specified, an initial collection of values.
75
def __nonzero__(self):
76
"""IntSets are false if empty, otherwise True.
84
return bool(self._val)
87
def __eq__(self, other):
89
if isinstance(other, IntSet):
90
return self._val == other._val
95
def __ne__(self, other):
96
return not self.__eq__(other)
99
def __contains__(self, i):
101
return self._val & (1L << i)
105
"""Return contents of set.
109
>>> list(IntSet([0, 1, 5, 7]))
114
# XXX: This is a bit slow
122
def update(self, to_add):
123
"""Add all the values from the sequence or intset to_add"""
124
if isinstance(to_add, IntSet):
125
self._val |= to_add._val
129
self._val |= (1L << i)
132
def add(self, to_add):
134
self._val |= (1L << to_add)
137
def remove(self, to_remove):
138
"""Remove one value from the set.
140
Raises KeyError if the value is not present.
144
Traceback (most recent call last):
145
File "/usr/lib/python2.4/doctest.py", line 1243, in __run
146
compileflags, 1) in test.globs
147
File "<doctest __main__.IntSet.remove[1]>", line 1, in ?
154
assert 0 <= to_remove
156
if not self._val & m:
157
raise KeyError(to_remove)
164
if __name__ == '__main__':