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

Nick Vatamaniuc vatamane at gmail.com
Tue Feb 6 07:23:13 EST 2007


On Feb 6, 5:22 am, Jonathan Fine <j... at pytex.org> wrote:
> Hello
>
> As part of the MathTran project I found myself
> wanting to maintain a bijection between long
> names and short names.
>    http://www.open.ac.uk/mathtran
>
> In other words, I wanted to have two dictionaries
> f and g such that
>    f[a] == b
>    g[b] == a
> are equivalent statements.
>
> A google search for biject.py and bijection.py
> produced no hits, so I suspect that this may not
> have been done before.
>
> I've written a partial implementation of this,
> and would appreciate comments.
>
> http://texd.cvs.sourceforge.net/texd/tex/util.py?revision=1.1&view=ma...http://texd.cvs.sourceforge.net/texd/test_tex/test_util.py?revision=1...
>
> Here's the code from test_util.py, that shows how it
> works.  The weakref stuff is so that there isn't a
> circular reference f to g to f.
> ===
> from tex.util import biject
>
> f, g = biject()
> assert f.inverse is g
> assert g.inverse is f
>
> f[1] = 2
> assert f[1] == 2
> assert g[2] == 1
> assert f.has_value(2)
>
> import weakref
>
> wr_g = weakref.ref(g)
> del g
> assert wr_g() == None
> assert f.inverse == None
> ===
>
> best regards
>
> Jonathan

Jonathan,

If you need to get a short name, given a long name or vice-verse _and_
the set of short names and long names is distinct (it would be
confusing if it wasn't!) then you can just have one dictionary, no
need to complicate things too much:
f[a]=b
f[b]=a
You won't know which is a short and which is a long based just on
this, so you need to keep track of it. But it will give you the
mapping.
Here is an example:
------------------------------------
>>> S=('a','b','d')
>>> L=('alpha,'beta','delta')
>>> f={}
>>> for i in range(3):
   ....:     f[S[i]]=L[i]
   ....:     f[L[i]]=S[i]
>>> f
{'a': 'alpha',
 'alpha': 'a',
 'b': 'beta',
 'beta': 'b',
 'd': 'delta',
 'delta': 'd'}

>>> f['b']
'beta'
>>> f['beta']
'b'
----------------------------------

Hope this helps,
And remember : "Simple Is Better Than Complex" [http://www.python.org/
doc/Humor.html#zen]

Nick Vatamaniuc






More information about the Python-list mailing list