[Tutor] Decision matrix

Erik Price eprice@ptc.com
Wed Feb 12 11:44:02 2003


Poor Yorick wrote:

> 
> STRING        FUNCTION
> 
> r                    function1
> rd                  function2
> rds                 function3
> d                    function4
> ds                  function5
> s                    function6
> 
> I've toyed with a series of if statements and considered constructing a 
> bitwise variable with which to index a dictionary of functions, and am 
> now looking for suggestions.  What would be the most eloquent way to 
> code this sort of decision matrix in Python?

Maybe I'm not entirely clear on what you're trying to do, but I'm
curious as to why you haven't tried the dictionary of functions
approach.  It seems like you have a one-to-one mapping with each of these.

|>>> def func1():
|...  return 1
|...
|>>> def func2():
|...  return 2
|...
|>>> def func3():
|...  return 3
|...
|>>> funcs = { 'r':func1, 'rd':func2, 'rds':func3 }
|>>> for i in funcs.keys():
|...  print "%s : %i" % (i, funcs[i]())
|...
|rd: 2
|r : 1
|rds : 3
|>>>




Erik

PS: Special thanks to the sages on this list for showing me how
functions are just another kind of object and can be referenced/called
in this fashion.