Multiway Branching

Bengt Richter bokr at oz.net
Sun Jan 8 15:51:47 EST 2006


On Sun, 8 Jan 2006 20:31:49 +0100, "Fredrik Lundh" <fredrik at pythonware.com> wrote:

>rshepard at 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.
>
>DATA_MAP = {
>    chr(32)+chr(32): 0,
>    chr(36)+chr(32): "natural",
>    ...
>    chr(32)+chr(1): 5,
>    chr(66)+chr(32): 0.167,
>}
>
>...
>
>row_value = DATA_MAP[source.read(2)]
>
># or: row_value = DATA_MAP.get(source.read(2), DEFAULT)
>
Much better than my version, since you went beyond the OP's code to what he said
he was trying to do ("look at two-byte pairs coming from a machine ... over the serial cable").
I just went for a direct translation of the code, which is nearly always a mistake.
I should know better. I guess I do, since I always rant about requirements ;-/
Also don't know why I chose to use dict([]) vs {}, since there's no bare key names to
clean the quotes off of. Oh well.

Regards,
Bengt Richter



More information about the Python-list mailing list