[Tutor] Re: data structure and algorithm

Kirby Urner urnerk@qwest.net
Tue, 26 Mar 2002 10:07:03 -0800


>
>I'll attempt some ASCII art here for the simple example (I hope the 
>spacing is retained properly):
>
>             --        --
>             |         | F       --
>             | B -f2-> |         | K
>             |         | G -f3-> | L
>             |         --        | B
>             |                   | N
>             |         --        --
>    A -f1->  |         | H
>                 | C -f2-> | I
>             |         | J
>             |         --
>             | D
>             |
>             | E
>             --

Many solutions possible.  Here's one possibility (sorry
if indentation is a bit off -- cut 'n paste sometimes
dicey):

     class Function:
        """
        Defines named function using a dictionary with
        lists of products keyed by symbol e.g. name='f1'
        mapdict = {'A':['B','C','D']} means A->f1->B,C,D
        """
         def __init__(self,name,mapdict):
             self.name    = name
             self.mapdict = mapdict
         def __call__(self,symbol):
            return self.mapdict.get(symbol,[])

     def mapit(functions, symbol, offset=""):
          """
          Recursively explores the reaction chains,
          using each function in succession, against
          the products (symbols) from a previous function
          (offset used for indentation)
          """
          if len(functions)==0:
                 return []
          f = functions[0]
           products = f(symbol)
           if len(products)>0:
              for p in products:
                print offset + symbol + '->' + f.name + '->' + p
                mapit(functions[1:],p,offset+"  ")

  >>> f1 = Function('f1',{'A':['B','C','D']})  # objects
  >>> f2 = Function('f2',{'B':['E','F','G']})
  >>> f3 = Function('f3',{'E':['K','L','M']})
  >>> reactions = [f1,f2,f3]  # to be passed to mapit()

  >>> mapit(reactions,'A')
  A->f1->B
   B->f2->E
      E->f3->K
     E->f3->L
      E->f3->M
    B->f2->F
   B->f2->G
  A->f1->C
  A->f1->D

Kirby