Welcome, guest | Sign In | My Account | Store | Cart

While programming an IPv4-Range class I stumbled upon the need for an efficient integer set type, which doesn't store individual items like the builtin set type does, but which only stores longs and ints, and does this in a run length encoded way to save space.

The following class implements such a beast as an immutable type, amongst support for minus and plus infinity to allow you to create infinitely sized sets. The set supports almost all operations that the builtin set type supports (which means excluding rich comparisons __gt__, __ge__, etc., for which I could find no meaningful interpretation).

The recipe is somewhat longish, but I couldn't think of some more elegant way to express most operations than by using predicate logic together with a set iterator, which keeps runtime for all set operations in O(n), except normalization, which is O(n*logn) because of the sort() operation on the list of ranges. Normalization is only done once on construction of the set; when a set is combined by some operation with another set, the output is automatically normalized.

The _Infinity private type is required to facilitate comparisons. _Infinity(True) will be smaller than any number and equal to itself, _Infinity(False) bigger than any number and equal to itself. This makes sorting easier.

Python, 533 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533``` ```# -*- coding: iso-8859-15 -*- """Immutable integer set type. Integer set class. Copyright (C) 2006, Heiko Wundram. Released under the MIT license: Copyright (c) 2006, Heiko Wundram. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # Version information # ------------------- __author__ = "Heiko Wundram " __version__ = "0.2" __revision__ = "7" __date__ = "2006-01-23" # Utility classes # --------------- class _Infinity(object): """Internal type used to represent infinity values.""" __slots__ = ["_neg"] def __init__(self,neg): self._neg = neg def __lt__(self,value): if not isinstance(value,(int,long,_Infinity)): return NotImplemented return ( self._neg and not ( isinstance(value,_Infinity) and value._neg ) ) def __le__(self,value): if not isinstance(value,(int,long,_Infinity)): return NotImplemented return self._neg def __gt__(self,value): if not isinstance(value,(int,long,_Infinity)): return NotImplemented return not ( self._neg or ( isinstance(value,_Infinity) and not value._neg ) ) def __ge__(self,value): if not isinstance(value,(int,long,_Infinity)): return NotImplemented return not self._neg def __eq__(self,value): if not isinstance(value,(int,long,_Infinity)): return NotImplemented return isinstance(value,_Infinity) and self._neg == value._neg def __ne__(self,value): if not isinstance(value,(int,long,_Infinity)): return NotImplemented return not isinstance(value,_Infinity) or self._neg <> value._neg def __repr__(self): return "None" # Constants # --------- _MININF = _Infinity(True) _MAXINF = _Infinity(False) # Integer set class # ----------------- class IntSet(object): """Integer set class with efficient storage in a RLE format of ranges. Supports minus and plus infinity in the range.""" __slots__ = ["_ranges","_min","_max","_hash"] def __init__(self,*args,**kwargs): """Initialize an integer set. The constructor accepts an unlimited number of arguments that may either be tuples in the form of (start,stop) where either start or stop may be a number or None to represent maximum/minimum in that direction. The range specified by (start,stop) is always inclusive (differing from the builtin range operator). Keyword arguments that can be passed to an integer set are min and max, which specify the minimum and maximum number in the set, respectively. You can also pass None here to represent minus or plus infinity, which is also the default. """ # Special case copy constructor. if len(args) == 1 and isinstance(args,IntSet): if kwargs: raise ValueError("No keyword arguments for copy constructor.") self._min = args._min self._max = args._max self._ranges = args._ranges self._hash = args._hash return # Initialize set. self._ranges = [] # Process keyword arguments. self._min = kwargs.pop("min",_MININF) self._max = kwargs.pop("max",_MAXINF) if self._min is None: self._min = _MININF if self._max is None: self._max = _MAXINF # Check keyword arguments. if kwargs: raise ValueError("Invalid keyword argument.") if not ( isinstance(self._min,(int,long)) or self._min is _MININF ): raise TypeError("Invalid type of min argument.") if not ( isinstance(self._max,(int,long)) or self._max is _MAXINF ): raise TypeError("Invalid type of max argument.") if ( self._min is not _MININF and self._max is not _MAXINF and self._min > self._max ): raise ValueError("Minimum is not smaller than maximum.") if isinstance(self._max,(int,long)): self._max += 1 # Process arguments. for arg in args: if isinstance(arg,(int,long)): start, stop = arg, arg+1 elif isinstance(arg,tuple): if len(arg) <> 2: raise ValueError("Invalid tuple, must be (start,stop).") # Process argument. start, stop = arg if start is None: start = self._min if stop is None: stop = self._max # Check arguments. if not ( isinstance(start,(int,long)) or start is _MININF ): raise TypeError("Invalid type of tuple start.") if not ( isinstance(stop,(int,long)) or stop is _MAXINF ): raise TypeError("Invalid type of tuple stop.") if ( start is not _MININF and stop is not _MAXINF and start > stop ): continue if isinstance(stop,(int,long)): stop += 1 else: raise TypeError("Invalid argument.") if start > self._max: continue elif start < self._min: start = self._min if stop < self._min: continue elif stop > self._max: stop = self._max self._ranges.append((start,stop)) # Normalize set. self._normalize() # Utility functions for set operations # ------------------------------------ def _iterranges(self,r1,r2,minval=_MININF,maxval=_MAXINF): curval = minval curstates = {"r1":False,"r2":False} imax, jmax = 2*len(r1), 2*len(r2) i, j = 0, 0 while i < imax or j < jmax: if i < imax and ( ( j < jmax and r1[i>>1][i&1] < r2[j>>1][j&1] ) or j == jmax ): cur_r, newname, newstate = r1[i>>1][i&1], "r1", not (i&1) i += 1 else: cur_r, newname, newstate = r2[j>>1][j&1], "r2", not (j&1) j += 1 if curval < cur_r: if cur_r > maxval: break yield curstates, (curval,cur_r) curval = cur_r curstates[newname] = newstate if curval < maxval: yield curstates, (curval,maxval) def _normalize(self): self._ranges.sort() i = 1 while i < len(self._ranges): if self._ranges[i] < self._ranges[i-1]: self._ranges[i-1] = (self._ranges[i-1], max(self._ranges[i-1], self._ranges[i])) del self._ranges[i] else: i += 1 self._ranges = tuple(self._ranges) self._hash = hash(self._ranges) def __coerce__(self,other): if isinstance(other,IntSet): return self, other elif isinstance(other,(int,long,tuple)): try: return self, self.__class__(other) except TypeError: # Catch a type error, in that case the structure specified by # other is something we can't coerce, return NotImplemented. # ValueErrors are not caught, they signal that the data was # invalid for the constructor. This is appropriate to signal # as a ValueError to the caller. return NotImplemented elif isinstance(other,list): try: return self, self.__class__(*other) except TypeError: # See above. return NotImplemented return NotImplemented # Set function definitions # ------------------------ def _make_function(name,type,doc,pall,pany=None): """Makes a function to match two ranges. Accepts two types: either 'set', which defines a function which returns a set with all ranges matching pall (pany is ignored), or 'bool', which returns True if pall matches for all ranges and pany matches for any one range. doc is the dostring to give this function. pany may be none to ignore the any match. The predicates get a dict with two keys, 'r1', 'r2', which denote whether the current range is present in range1 (self) and/or range2 (other) or none of the two, respectively.""" if type == "set": def f(self,other): coerced = self.__coerce__(other) if coerced is NotImplemented: return NotImplemented other = coerced newset = self.__class__.__new__(self.__class__) newset._min = min(self._min,other._min) newset._max = max(self._max,other._max) newset._ranges = [] for states, (start,stop) in \ self._iterranges(self._ranges,other._ranges, newset._min,newset._max): if pall(states): if newset._ranges and newset._ranges[-1] == start: newset._ranges[-1] = (newset._ranges[-1],stop) else: newset._ranges.append((start,stop)) newset._ranges = tuple(newset._ranges) newset._hash = hash(self._ranges) return newset elif type == "bool": def f(self,other): coerced = self.__coerce__(other) if coerced is NotImplemented: return NotImplemented other = coerced _min = min(self._min,other._min) _max = max(self._max,other._max) found = not pany for states, (start,stop) in \ self._iterranges(self._ranges,other._ranges,_min,_max): if not pall(states): return False found = found or pany(states) return found else: raise ValueError("Invalid type of function to create.") f.func_name = name f.func_doc = doc return f # Intersection. __and__ = _make_function("__and__","set", "Intersection of two sets as a new set.", lambda s: s["r1"] and s["r2"]) __rand__ = _make_function("__rand__","set", "Intersection of two sets as a new set.", lambda s: s["r1"] and s["r2"]) intersection = _make_function("intersection","set", "Intersection of two sets as a new set.", lambda s: s["r1"] and s["r2"]) # Union. __or__ = _make_function("__or__","set", "Union of two sets as a new set.", lambda s: s["r1"] or s["r2"]) __ror__ = _make_function("__ror__","set", "Union of two sets as a new set.", lambda s: s["r1"] or s["r2"]) union = _make_function("union","set", "Union of two sets as a new set.", lambda s: s["r1"] or s["r2"]) # Difference. __sub__ = _make_function("__sub__","set", "Difference of two sets as a new set.", lambda s: s["r1"] and not s["r2"]) __rsub__ = _make_function("__rsub__","set", "Difference of two sets as a new set.", lambda s: s["r2"] and not s["r1"]) difference = _make_function("difference","set", "Difference of two sets as a new set.", lambda s: s["r1"] and not s["r2"]) # Symmetric difference. __xor__ = _make_function("__xor__","set", "Symmetric difference of two sets as a new set.", lambda s: s["r1"] ^ s["r2"]) __rxor__ = _make_function("__rxor__","set", "Symmetric difference of two sets as a new set.", lambda s: s["r1"] ^ s["r2"]) symmetric_difference = _make_function("symmetric_difference","set", "Symmetric difference of two sets as a new set.", lambda s: s["r1"] ^ s["r2"]) # Containership testing. __contains__ = _make_function("__contains__","bool", "Returns true if self is superset of other.", lambda s: s["r1"] or not s["r2"]) issubset = _make_function("issubset","bool", "Returns true if self is subset of other.", lambda s: s["r2"] or not s["r1"]) istruesubset = _make_function("istruesubset","bool", "Returns true if self is true subset of other.", lambda s: s["r2"] or not s["r1"], lambda s: s["r2"] and not s["r1"]) issuperset = _make_function("issuperset","bool", "Returns true if self is superset of other.", lambda s: s["r1"] or not s["r2"]) istruesuperset = _make_function("istruesuperset","bool", "Returns true if self is true superset of other.", lambda s: s["r1"] or not s["r2"], lambda s: s["r1"] and not s["r2"]) overlaps = _make_function("overlaps","bool", "Returns true if self overlaps with other.", lambda s: True, lambda s: s["r1"] and s["r2"]) # Comparison. __eq__ = _make_function("__eq__","bool", "Returns true if self is equal to other.", lambda s: not ( s["r1"] ^ s["r2"] )) __ne__ = _make_function("__ne__","bool", "Returns true if self is different to other.", lambda s: True, lambda s: s["r1"] ^ s["r2"]) # Clean up namespace. del _make_function # Define other functions. def inverse(self): """Inverse of set as a new set.""" newset = self.__class__.__new__(self.__class__) newset._min = self._min newset._max = self._max newset._ranges = [] laststop = self._min for r in self._ranges: if laststop < r: newset._ranges.append((laststop,r)) laststop = r if laststop < self._max: newset._ranges.append((laststop,self._max)) return newset __invert__ = inverse # Hashing # ------- def __hash__(self): """Returns a hash value representing this integer set. As the set is always stored normalized, the hash value is guaranteed to match for matching ranges.""" return self._hash # Iterating # --------- def __len__(self): """Get length of this integer set. In case the length is larger than 2**31 (including infinitely sized integer sets), it raises an OverflowError. This is due to len() restricting the size to 0 <= len < 2**31.""" if not self._ranges: return 0 if self._ranges is _MININF or self._ranges[-1] is _MAXINF: raise OverflowError("Infinitely sized integer set.") rlen = 0 for r in self._ranges: rlen += r-r if rlen >= 2**31: raise OverflowError("Integer set bigger than 2**31.") return rlen def len(self): """Returns the length of this integer set as an integer. In case the length is infinite, returns -1. This function exists because of a limitation of the builtin len() function which expects values in the range 0 <= len < 2**31. Use this function in case your integer set might be larger.""" if not self._ranges: return 0 if self._ranges is _MININF or self._ranges[-1] is _MAXINF: return -1 rlen = 0 for r in self._ranges: rlen += r-r return rlen def __nonzero__(self): """Returns true if this integer set contains at least one item.""" return bool(self._ranges) def __iter__(self): """Iterate over all values in this integer set. Iteration always starts by iterating from lowest to highest over the ranges that are bounded. After processing these, all ranges that are unbounded (maximum 2) are yielded intermixed.""" ubranges = [] for r in self._ranges: if r is _MININF: if r is _MAXINF: ubranges.extend(([0,1],[-1,-1])) else: ubranges.append([r-1,-1]) elif r is _MAXINF: ubranges.append([r,1]) else: # Little hackish, but bombs out on 32-bit platforms if using # xrange. val = r while val < r: yield val val += 1 if ubranges: while True: for ubrange in ubranges: yield ubrange ubrange += ubrange # Printing # -------- def __repr__(self): """Return a representation of this integer set. The representation is executable to get an equal integer set.""" rv = [] for start, stop in self._ranges: if ( isinstance(start,(int,long)) and isinstance(stop,(int,long)) and stop-start == 1 ): rv.append("%r" % start) elif isinstance(stop,(int,long)): rv.append("(%r,%r)" % (start,stop-1)) else: rv.append("(%r,%r)" % (start,stop)) if self._min is not _MININF: rv.append("min=%r" % self._min) if self._max is not _MAXINF: rv.append("max=%r" % self._max) return "%s(%s)" % (self.__class__.__name__,",".join(rv)) if __name__ == "__main__": # Little test script demonstrating functionality. x = IntSet((10,20),30) y = IntSet((10,20)) z = IntSet((10,20),30,(15,19),min=0,max=40) print x print x&110 print x|110 print x^(15,25) print x-12 print 12 in x print x.issubset(x) print y.issubset(x) print x.istruesubset(x) print y.istruesubset(x) for val in x: print val print x.inverse() print x == z print x == y print x <> y print hash(x) print hash(z) print len(x) print x.len() ```

Implementing the IPv4-type on top of this isn't hard, the intset type is well suited for extension because all operations automatically return the subtype that is requested. By generalizing a bit, you could even extend intset to be a set type for any form of value that implements comparison operations. Heiko Wundram (author) 15 years, 10 months ago

Slight changes to the algorithm to make it slightly easier to read... While pondering over the code now that I posted it, I guess that it's a somewhat strange design decision to store containership in a tuple. It's much better to use a dictionary for that, and the following adapted _iterranges() does exactly this:

``````def _iterranges(self,r1,r2,minval=_MININF,maxval=_MAXINF):
curval = minval
curstates = {"r1":False,"r2":False}
imax, jmax = 2*len(r1), 2*len(r2)
i, j = 0, 0
while i &lt; imax or j &lt; jmax:
if i &lt; imax and ( ( j &lt; jmax and
r1[i>>1][i&amp;1] &lt; r2[j>>1][j&amp;1] ) or
j == jmax ):
cur_r1 = r1[i>>1][i&amp;1]
if curval &lt; cur_r1:
if cur_r1 > maxval:
break
yield curstates, (curval,cur_r1)
curval = cur_r1
curstates["r1"] = not (i&amp;1)
i += 1
else:
cur_r2 = r2[j>>1][j&amp;1]
if curval &lt; cur_r2:
if cur_r2 > maxval:
break
yield curstates, (curval,cur_r2)
curval = cur_r2
curstates["r2"] = not (j&amp;1)
j += 1
if curval &lt; maxval:
yield curstates, (curval,maxval)
``````

When you adapt _iterranges with that code, you'll need to adapt the function definitions too:

``````__and__ = _make_function("__and__","set",
"Intersection of two sets as a new set.",
lambda s: s["r1"] and s["r2"])
__rand__ = _make_function("__rand__","set",
"Intersection of two sets as a new set.",
lambda s: s["r1"] and s["r2"])
__contains__ = _make_function("__contains__","bool",
"Returns true if self is superset of other.",
lambda s: s["r1"] or not s["r2"])
__or__ = _make_function("__or__","set",
"Union of two sets as a new set.",
lambda s: s["r1"] or s["r2"])
__ror__ = _make_function("__ror__","set",
"Union of two sets as a new set.",
lambda s: s["r1"] or s["r2"])
__sub__ = _make_function("__sub__","set",
"Difference of two sets as a new set.",
lambda s: s["r1"] and not s["r2"])
__rsub__ = _make_function("__rsub__","set",
"Difference of two sets as a new set.",
lambda s: s["r2"] and not s["r1"])
__xor__ = _make_function("__xor__","set",
``````

(comment continued...) Heiko Wundram (author) 15 years, 10 months ago

(...continued from previous comment)

``````                         "Symmetric difference of two sets as a new set.",
lambda s: s["r1"] ^ s["r2"])
__rxor__ = _make_function("__rxor__","set",
"Symmetric difference of two sets as a new set.",
lambda s: s["r1"] ^ s["r2"])
difference = _make_function("difference","set",
"Difference of two sets as a new set.",
lambda s: s["r1"] and not s["r2"])
intersection = _make_function("intersection","set",
"Intersection of two sets as a new set.",
lambda s: s["r1"] and s["r2"])
issubset = _make_function("issubset","bool",
"Returns true if self is subset of other.",
lambda s: s["r2"] or not s["r1"])
issuperset = _make_function("issuperset","bool",
"Returns true if self is superset of other.",
lambda s: s["r1"] or not s["r2"])
symmetric_difference = _make_function("symmetric_difference","set",
"Symmetric difference of two sets as a new set.",
lambda s: s["r1"] ^ s["r2"])
union = _make_function("union","set",
"Union of two sets as a new set.",
lambda s: s["r1"] or s["r2"])
``````

which look quite a bit cleaner now, in my taste. Heiko Wundram (author) 15 years, 10 months ago

... and which I have now implemented in the recipe itself. I didn't know you could edit recipe's here. ;-) Created by Heiko Wundram on Thu, 12 Jan 2006 (PSF)

### Required Modules

• (none specified)