Multiway Branching

Justin Azoff justin.azoff at gmail.com
Sun Jan 8 14:22:10 EST 2006


rshep... 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.
>
> Rich
>
> --
> Richard B. Shepard, Ph.D.               |   Author of "Quantifying Environmental
> Applied Ecosystem Services, Inc. (TM)   |  Impact Assessments Using Fuzzy Logic"
> <http://www.appl-ecosys.com>     Voice: 503-667-4517         Fax: 503-667-8863

Use a dictionary:

byte_values = {
   (32,32)  : 0,
   (36,32)  : 'natural',
   (32,1 )  : 5,
}

row_value = byte_values[byte1,byte2]

-- 
- Justin




More information about the Python-list mailing list