diff options
-rw-r--r-- | src/python/lmi/test/util.py | 35 |
1 files changed, 33 insertions, 2 deletions
diff --git a/src/python/lmi/test/util.py b/src/python/lmi/test/util.py index 7574751..6bce3c6 100644 --- a/src/python/lmi/test/util.py +++ b/src/python/lmi/test/util.py @@ -420,8 +420,20 @@ class PackedSequence(object): return "%s%s" % (n, self.item) return "" + def __add__(self, other): + if self.item == other.item: + return self.__class__(self.item, self.num + other.num) + else: + raise TypeError("items cannot be added") + + def __nonzero__(self): + return bool(self.num) + + def __repr__(self): + return "%s(%s,%s)" % (self.__class__.__name__, self.item, self.num) + def __init__(self, seq=None): - self._items = self._parse(seq) + self._items = self._squash(self._parse(seq)) if seq else [] def __iter__(self): return self @@ -432,11 +444,30 @@ class PackedSequence(object): def __str__(self): return ",".join([str(i) for i in self._items]) + def _squash(self, sparse): + """ + Squash items, i.e. "b,1a,0a,0a,a,2a" to "1b,4a" + """ + comp = [] + while sparse: + nxt = sparse.pop() + if not nxt: # skip zero items + continue + elif comp: + try: + comp[-1] += nxt + except TypeError: # cannot add -> append + comp.append(nxt) + else: + comp.append(nxt) + comp.reverse() + return comp + def _parse(self, seq): """ Parse sequence string """ - return [self._parse1(itm) for itm in seq.split(",")] if seq else [] + return [self._parse1(itm) for itm in seq.split(",")] def _parse1(self, itm): ns = "" |