Two mappings inverse to each other: f, g = biject()

Jonathan Fine jfine at pytex.org
Wed Feb 7 13:52:48 EST 2007


bearophileHUGS at lycos.com wrote:

>>A google search for biject.py and bijection.py
>>produced no hits, so I suspect that this may not
>>have been done before.
> 
> 
> There are few (good too) implementations around, but they are called
> bidict or bidirectional dicts. Sometimes I use this implementation,
> with few changes:
> http://www.radlogic.com.au/releases/two_way_dict.py

Thank you for this.  You are quite right, a dictionary
is a particular type of mapping.  A mapping with an
inverse is called (at least by me) a bijection.  Therefore,
as you say, bidict or something similar is correct for
a bijection that is based on dictionaries.

I had a look at the code in radlogic.  There, the
design philosophy is to add 'inverse operations' to
a dictionary.  Thus, it adds a method reversed_items.

In my code, I used a different philosophy, which
comes down to this.  If a mapping is by design a
bijection, then it should have an inverse method
that gives the inverse mapping.  This preserves the
symmetry between a mapping and its inverse.  (The
inverse has an inverse, which is the original mapping.)

Therefore, my semantics comes down to
   f, g = bidict()  # Use the better name.
   assert f = g.inverse
   assert g = f.inverse
and also
   f[a] = b if and only if g[b] = a

By the way, it turns out that a bidict is not what
my application needs.  But I find it an interesting
problem, and time spent on it I do not consider
wasted.

Best regards

Jonathan






More information about the Python-list mailing list