Help with an algorithm wanted
Niklas Frykholm
r2d2 at acc.umu.se
Thu Jun 27 04:05:46 EDT 2002
[Russell E. Owen]:
> I'd like some help solving a problem in Python.
>
> The basic idea is I have an item of data that can be represented in any
> of four ways: A,B,C and D. I also have conversion functions between
> certain pairs of representations, such that there's always a path
> between any two data representations. In this case suppose I know A<->C,
> B<->C and C<->D, or graphically:
>
> A <--+
> +--> C <---> D
> B <--+
>
> I'd like to create objects that have one of these items (A,B,C,D) as a
> given, then be able to query any such object for any data representation.
Here is one possible solution. Given a set of classes A, B, C... and
known conversion functions A.to_B, B.to_C, etc this code creates all
derived conversion functions (such as A.to_C). It thus solves the problem
statically. (In some cases a dynamic solution is preferrable.)
def add_conversion(fromm, via, to):
"Add conversion from class fromm to class to, via class via."
def convert(self):
via_object = getattr(self, "to_" + via)()
return getattr(via_object, "to_" + to)()
setattr(globals()[fromm], "to_" + to, convert)
def has_conversion(fromm, to):
"Is there a conversion function from class fromm to class to?"
return hasattr(globals()[fromm], "to_" + to)
def conversions(klass):
"Returns all the conversion functions of klass."
l = filter(lambda s: s.startswith('to_'), dir(globals()[klass]))
return map(lambda s: s[3:len(s)], l)
def create_quick_conversions(classes):
"Create all possible derived conversions for the set of classes."
for via in classes:
tos = conversions(via)
for fromm in classes:
if fromm != via and has_conversion(fromm, via):
for to in tos:
if not has_conversion(fromm, to):
add_conversion(fromm, via, to)
# end of for
create_quick_conversions(["A", "B", "C", "D"])
// Niklas
More information about the Python-list
mailing list