[Edu-sig] Reversing dictionaries, closures, permutations etc.
Kirby Urner
urnerk at qwest.net
Sat Jan 24 12:51:53 EST 2004
> > What I'm thinking about in this thread is a way to define functions and
> > inverse functions in a namespace, then pass them to a class P so that
> > operator overloading will allow:
>
> I have to confess that you lost me somewhere below this point (I'll
> reread it until I get it), but this is the sort of thing UserDict is for,
> right?
> I know Zope subclasses it to get the PersistentMapping class -- it
> gives you the basic dictionary interface, which you can then build
> on.
>
> Cheers,
> Terry
>
The way I factored it, I wanted the P-class to accept /any/ pair of
functions f, invf, where invf is the inverse of f.
If f is based on a dictionary lookup (e.g. a permutations), then invf could
be defined using a dictionary inverter (example in previous post).
But f might just be an algebraic rule, e.g.:
>>> def f(x): return 2.0 * x
>>> def invf(x): return x / 2.0
>>> p1 = P(f,invf) # <-- wrapping in P-class to get operator overloading
>>> p1(4) # <-- using __call__
8.0
>>> p2 = ~p1 # <-- using __invert__
>>> p2(8.0)
4.0
>>> p3 = (p2 * p1 * ~p2) # <-- using __mul__ to call self.compose()
>>> p3(10)
20.0
>>> map((p1 * ~p1), [4,3,9,10,0.5,-9.1]) <-- ditto
[4.0, 3.0, 9.0, 10.0, 0.5, -9.0999999999999996]
The last command reminds us that f(decimal)->binary does not itself have an
exact inverse function in the floating point numbers.
Kirby
More information about the Edu-sig
mailing list