Writing more efficient code

John Machin sjmachin at lexicon.net
Mon Jan 1 20:20:10 EST 2007


gonzlobo wrote:
> Greetings, and happyNewYear to all.
>
> I picked up Python a few weeks ago, and have been able to parse large
> files and process data pretty easily, but I believe my code isn't too
> efficient. I'm hoping dictionaries will help out, but I'm not sure the
> best way to implement them.
>
> I've been using a bunch of nested if/elif/else statements to select
> slices (0317 & 03de) from a file, then parse the data (aa, hh, bb,
> d2-d9) into parameters (a = airspeed, h = heading) & flags.
>
> #sample file contents
> 0000007d 03 0317 aa aa aa aa aa hh hh hh bb bb
> 0000007e 06 03de d2 d3 d4 d5 d6 d7 d8 d9 10 11

Do you have the original file from which this hex dump was made? It may
be a lot easier to write the code to pick that apart using the struct
module's unpack function than fiddling with the hex dump. It would
probably run faster as well.

>
> # some pseudo code
> if PID == '03de':
>     flapsCmd = int(d3, 16)
>    if flapsCmd == 0xc0:
>       <flaps up code>
>    elif flapsCmd == 0x03:
>       <flaps down code>
> if PID == '0317':
>    airspeed == 'combine aa for airspeed & multiply by 0.1'

*five* bytes for airspeed? Are they ascii characters e.g. "01234"
meaning 123.4?

>    heading == 'combine hh for heading'
>    mach == 'combine bb for mach & multiply by 0.01'
>
> Might dictionaries help in this case... say Label0317(parameterName,
> slice (d3), scaleFactor(0.1))... I'd like to use them if they'll
> replace the dozens of nested conditionals.  I have roughly 75
> different parameters to decode from a file containing ~2.5 million
> lines of data.
>
> I know my pseudo code lacks details, but hopefully I'm getting my
> point across...

It would help if you gave some more precise info on what format the
individual fields can take.

Cheers,
John




More information about the Python-list mailing list