Multiway Branching

Bengt Richter bokr at oz.net
Sun Jan 8 21:36:14 CET 2006


On 8 Jan 2006 18:59:28 GMT, rshepard at salmo.appl-ecosys.com wrote:

>  I need to look at two-byte pairs coming from a machine, and interpret the
>meaning based on the relative values of the two bytes. In C I'd use a switch
>statement. Python doesn't have such a branching statement. I have 21
>comparisons to make, and that many if/elif/else statements is clunky and
>inefficient. Since these data are coming from an OMR scanner at 9600 bps (or
>faster if I can reset it programmatically to 38K over the serial cable), I
>want a fast algorithm.
>
>  The data are of the form:
>
>  if byte1 == 32 and byte2 == 32:
>	row_value = 0
>  elif byte1 == 36 and byte2 == 32:
>	row_value = "natural"
>   ...
>  elif byte1 == 32 and byte2 == 1:
>	row_value = 5
>  elif byte1 == 66 and byte2 == 32:
>	row_value = 0.167
>
>  There are two rows where the marked response equates to a string and 28
>rows where the marked response equates to an integer (1-9) or float of
>defined values.
>
>  Suggestions appreciated.
>
Set up a dict to map your byte pairs to values, e.g.,

 >>> pairvalues = dict([
 ...     ((32,32), 0),
 ...     ((36,32), "natural"),
 ...     # ...
 ...     ((32, 1), 5),
 ...     ((66,32), 0.167)
 ... ])

Then you can access the values like:

 >>> row_value = pairvalues.get((36,32), '<default>')
 >>> row_value
 'natural'

The .get method allows you to specify a default, in case you get an unexpected pair.
You could also use pairvalues[(byte1,byte2)] and catch the KeyError exception for
unexpected pairs.

 >>> for byte1, byte2 in (66,32), (32,1), (36,32), (32,32), (20,20):
 ...     print '%10s => %r' %((byte1,byte2), pairvalues.get((byte1,byte2), 'DEFAULT ??'))
 ...
   (66, 32) => 0.16700000000000001
    (32, 1) => 5
   (36, 32) => 'natural'
   (32, 32) => 0
   (20, 20) => 'DEFAULT ??'

HTH

Regards,
Bengt Richter



More information about the Python-list mailing list