Goulib.container module

advanced containers : Record (struct), SortedCollection, and INFINITE Sequence

class Goulib.container.Record(*args, **kwargs)[source]

Bases: collections.OrderedDict

__init__(*args, **kwargs)[source]
__getattr__(name)[source]
__setattr__(name, value)[source]
__str__()[source]
__class__

alias of type

__contains__()

True if D has a key k, else False.

__delattr__

Implement delattr(self, name).

__delitem__

Delete self[key].

__dir__() → list

default dir() implementation

__eq__

Return self==value.

__format__()

default object formatter

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__()

x.__getitem__(y) <==> x[y]

__gt__

Return self>value.

__hash__ = None
__iter__

Implement iter(self).

__le__

Return self<=value.

__len__

Return len(self).

__lt__

Return self<value.

__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Return state information for pickling

__reduce_ex__()

helper for pickle

__repr__

Return repr(self).

__reversed__() <==> reversed(od)
__setitem__

Set self[key] to value.

__sizeof__()
clear() → None. Remove all items from od.
copy() → a shallow copy of od
fromkeys(S[, v]) → New ordered dictionary with keys from S.

If not specified, the value defaults to None.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
items()
keys()
move_to_end()

Move an existing element to the end (or beginning if last==False).

Raises KeyError if the element does not exist. When last=True, acts like a fast version of self[key]=self.pop(key).

pop(k[, d]) → v, remove specified key and return the corresponding

value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), return and remove a (key, value) pair.

Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault(k[, d]) → od.get(k,d), also set od[k]=d if k not in od
update()
values()
class Goulib.container.SortedCollection(iterable=(), key=None)[source]

Bases: object

Sequence sorted by a key function.

SortedCollection() is much easier to work with than using bisect() directly. It supports key functions like those use in sorted(), min(), and max(). The result of the key function call is saved so that keys can be searched efficiently.

Instead of returning an insertion-point which can be hard to interpret, the five find-methods return a specific item in the sequence. They can scan for exact matches, the last item less-than-or-equal to a key, or the first item greater-than-or-equal to a key.

Once found, an item’s ordinal position can be located with the index() method. New items can be added with the insert() and insert_right() methods. Old items can be deleted with the remove() method.

The usual sequence methods are provided to support indexing, slicing, length lookup, clearing, copying, forward and reverse iteration, contains checking, item counts, item removal, and a nice looking repr.

Finding and indexing are O(log n) operations while iteration and insertion are O(n). The initial sort is O(n log n).

The key function is stored in the ‘key’ attibute for easy introspection or so that you can assign a new key function (triggering an automatic re-sort).

In short, the class was designed to handle all of the common use cases for bisect but with a simpler API and support for key functions.

>>> from pprint import pprint
>>> from operator import itemgetter
>>> s = SortedCollection(key=itemgetter(2))
>>> for record in [
...         ('roger', 'young', 30),
...         ('angela', 'jones', 28),
...         ('bill', 'smith', 22),
...         ('david', 'thomas', 32)]:
...     s.insert(record)
>>> pprint(list(s))         # show records sorted by age
[('bill', 'smith', 22),
 ('angela', 'jones', 28),
 ('roger', 'young', 30),
 ('david', 'thomas', 32)]
>>> s.find_le(29)           # find oldest person aged 29 or younger
('angela', 'jones', 28)
>>> s.find_lt(28)           # find oldest person under 28
('bill', 'smith', 22)
>>> s.find_gt(28)           # find youngest person over 28
('roger', 'young', 30)
>>> r = s.find_ge(32)       # find youngest person aged 32 or older
>>> s.index(r)              # get the index of their record
3
>>> s[3]                    # fetch the record at that index
('david', 'thomas', 32)
>>> s.key = itemgetter(0)   # now sort by first name
>>> pprint(list(s))
[('angela', 'jones', 28),
 ('bill', 'smith', 22),
 ('david', 'thomas', 32),
 ('roger', 'young', 30)]
__init__(iterable=(), key=None)[source]
key

key function

clear()[source]
copy()[source]
__len__()[source]
__getitem__(i)[source]
__iter__()[source]
__reversed__()[source]
__repr__()[source]
__reduce__()[source]
__contains__(item)[source]
index(item)[source]

Find the position of an item. Raise ValueError if not found.

count(item)[source]

Return number of occurrences of item

insert(item)[source]

Insert a new item. If equal keys are found, add to the left

insert_right(item)[source]

Insert a new item. If equal keys are found, add to the right

pop(i=-1)[source]
remove(item)[source]

Remove first occurence of item. Raise ValueError if not found

find(k)[source]

Return first item with a key == k. Raise ValueError if not found.

find_le(k)[source]

Return last item with a key <= k. Raise ValueError if not found.

find_lt(k)[source]

Return last item with a key < k. Raise ValueError if not found.

find_ge(k)[source]

Return first item with a key >= equal to k. Raise ValueError if not found

find_gt(k)[source]

Return first item with a key > k. Raise ValueError if not found

__class__

alias of type

__delattr__

Implement delattr(self, name).

__dir__() → list

default dir() implementation

__eq__

Return self==value.

__format__()

default object formatter

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__le__

Return self<=value.

__lt__

Return self<value.

__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce_ex__()

helper for pickle

__setattr__

Implement setattr(self, name, value).

__sizeof__() → int

size of object in memory, in bytes

__str__

Return str(self).

class Goulib.container.Sequence(iterf=None, itemf=None, containf=None, desc='')[source]

Bases: object

combines a generator and a read-only list used for INFINITE numeric (integer) sequences

Parameters:
  • iterf – optional iterator, or a function returning an iterator
  • itemf – optional function(i) returning the i-th element
  • containf – optional function(n) return bool True if n belongs to Sequence
  • desc – string description
__init__(iterf=None, itemf=None, containf=None, desc='')[source]
Parameters:
  • iterf – optional iterator, or a function returning an iterator
  • itemf – optional function(i) returning the i-th element
  • containf – optional function(n) return bool True if n belongs to Sequence
  • desc – string description
__repr__()[source]
__iter__()[source]

reset the generator :return: a tee-ed copy of iterf

__getitem__(i)[source]
index(v)[source]
__contains__(n)[source]
__add__(other)[source]
__sub__(other)[source]
__or__(other)[source]
Returns:Sequence with items from both operands
__and__(other)[source]
Returns:Sequence with items in both operands
__mod__(other)[source]
Returns:Sequence with items from left operand not in right
apply(f, containf=None, desc='')[source]
__class__

alias of type

__delattr__

Implement delattr(self, name).

__dir__() → list

default dir() implementation

__eq__

Return self==value.

__format__()

default object formatter

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__le__

Return self<=value.

__lt__

Return self<value.

__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

helper for pickle

__reduce_ex__()

helper for pickle

__setattr__

Implement setattr(self, name, value).

__sizeof__() → int

size of object in memory, in bytes

__str__

Return str(self).

filter(f, desc='')[source]
accumulate(op=<built-in function add>, skip_first=False)[source]
pairwise(op, skip_first=False)[source]
sort(key=None, buffer=100)[source]
unique(buffer=100)[source]
Parameters:buffer – int number of last elements found.

if two identical elements are separated by more than this number of elements in self, they might be generated twice in the resulting Sequence :return: Sequence made of unique elements of this one