Module equivalence :: Class Equivalence
[hide private]
[frames] | no frames]

Class Equivalence

source code

object --+
         |
        Equivalence

Representation of a general equivalence relation.

An Equivalence instance can be used to maintain a partition of objects into equivalence sets. Two objects x and y are considered equivalent either implicitly through a key function or explicitly. For the implicit case, x and y are equivalent if key(x) == key(y) for some provided function key (by default the identity function lambda x:x). For the explicit case, x and y are considered equivalent after a call to merge(x,y), regardless of their keys.

This class makes sure that the equivalence properties (reflexivity, symmetry, transitivity) are maintained, provided that key(x) remains fixed for a given object x (i.e. key is deterministic and does not depend on mutable state of x).



Instance Methods [hide private]
 
__init__(self, key=None)
Initialize a new equivalence relation.
source code
 
update(self, *objects)
Update this equivalence with the given objects.
source code
 
merge(self, *objects)
Merge all the given objects into the same equivalence set.
source code
bool
are_equivalent(self, *objects)
Checks whether all objects are equivalent.
source code
list of lists
partitions(self, objects=None)
Returns the partitioning of objects into equivalence groups.
source code
set
partition(self, obj)
Return the set of objects in the equivalence that are equivalent to obj.
source code
 
partition_key(self, obj)
Return the key of the equivalence partition obj belongs to.
source code

Inherited from object: __delattr__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __str__

Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, key=None)
(Constructor)

source code 
Initialize a new equivalence relation.
Parameters:
  • key - A callable that takes a single argument and returns its equivalence key (default: identity function).
Overrides: object.__init__

are_equivalent(self, *objects)

source code 

Checks whether all objects are equivalent.

An object doesn't have to be inserted first (through update or merge) in order to appear as an argument. In this case, its key is used to determine the partition it would belong if it was inserted.

Returns: bool

partitions(self, objects=None)

source code 
Returns the partitioning of objects into equivalence groups.
Parameters:
  • objects (Iterable or None) - If not None, it must be an iterable of objects to be partitioned. Otherwise, it defaults to the set of objects already inserted in the equivalence (through update and merge).
Returns: list of lists
A list of partitions, each partition being a list of objects.