Find the closest relative
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Fri May 25 07:08:19 EDT 2007
En Fri, 25 May 2007 05:09:00 -0300, jm.suresh at no.spam.gmail.com
<jm.suresh at gmail.com> escribió:
> Vehicle
> |
> |--- Two Wheeler
> | |
> | |--- BatteryPowered
> | |--- PetrolPowered
> | |--- DieselPowered
> |
> |--- Three Wheeler
> | |
> | |--- AutoRicksaw
> |
> |--- Four Wheeler
> | |
> | |--- GeneralTrans
> | | |--- Car
> | | |--- Car1
> | | |--- Car2
> | | |--- Car3
> | |
> | |--- PublicTrans
> | | |--- Bus
> | | |--- Bus1
> | | |--- Bus2
> | |--- Goods
> | |--- Lorry
> |--- Lorry1
> |--- Lorry2
> |--- Lorry3
>
> Now given one instance of some type, I want to choose between second
> and third, whichever
> is closest relative to the first object.
> Eg.
> Instance(Car1), Instance(Lorry1), Instance(AutoRicksaw) =>
> Instance(Lorry1)
If your classes actually form a tree (you have only single inheritance)
then you may use the mro():
Car1.mro() = [Car, GeneralTrans, FourWheeler, Vehicle, object]
Lorry1.mro() = [Lorry, Goods, FourWheeler, Vehicle, object]
AutoRicksaw.mro() = [ThreeWeeler, Vehicle, object]
Now you have to find the first item in Lorr1.mro that appears also in
Car1.mro, and the same for AutoRicksaw.mro; the least index on Car1.mro
wins (Or the least index in the other list; or the least sum; that depends
on your exact definition of "closest relative").
(Under the Argentinian law, you measure how "close" two relatives are,
starting with one person, going up the tree until you find a common
ancestor, and going down to the other person. That is, summing up the
indices on both "mro" lists for the common ancestor).
--
Gabriel Genellina
More information about the Python-list
mailing list