Help with a reverse dictionary lookup

Scott David Daniels scott.daniels at acm.org
Fri Mar 10 06:52:20 CET 2006


rh0dium wrote:
> Basically there are multiple combinatories here - I was hoping someone
> could point me to a general approach.  Writing the actual funtion is
> not necessary - as you pointed out I can certainly do that. Here is my
> problem -  I did exactly as you and said OK I can
> 
> if Foundry==None and Process==None:
> 
> elif Foundy==None and Process!=None:
> 
> elif Foundy!=None and Process==None:
> 
> elif Foundy!=None and Process!=None:
> 
> But this seems very ugly...  And if I want to do this for the three
> areas, it seems very repetitive.  I was looking for a better way to
> break this down which is reusable.

First, use identity comparisons with None.
Second, I'd do it like this:

     if Foundry is None:
         # common ~Foundry stuff
         if Process is None:
             pass # ~F & ~P stuff
         else:
             pass # ~F & P stuff
         # common ~Foundry stuff needing Process resolved
     else:
         # common Foundry stuff
         if Process is None:
             pass # F & ~P stuff
         else:
             pass # F & P stuff
         # common ~Foundry stuff needing Process resolved

Unless there is more Process / ~Process common work, in which
case re-nest.  Don't be scared to write "the obvious" in Python.

Second, once it grows to over two, think about doing things by cases:

     def AllTrue(Foundry, Process, Vendor):
         print 'Triple', (Foundry, Process, Vendor)
     def NoVendor(Foundry, Process, Vendor):
         print 'Pair', (Foundry, Process)
     ...
     def Nothing(Foundry, Process, Vendor):
         print 'Nada'
     behavior = {0: AllTrue, 1:NoVendor, 2:NoProcess, 3: OnlyFoundry,
                 4: NoFoundry, 5:OnlyProcess, 6:OnlyVendor, 7: Nothing}
     def dispatch(f, p, v):
         return behavior[((f is None) * 2 + (p is None)) * 2
                         + (v is None)](f, p, v)
     ...
     dispatch('Intel', 'Silicon', None)


--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list