Register
Login

Python Comprehensions
19.6.2009

I haven't posted in a while, so here's a fun fact for the day: Although they probably aren't the best way to do most problems, they sure are cool - Python Comprehensions. When you combine a list comprehension with the reduce() function, the one-liner possibilities are endless. For example, if you need a quick and dirty way to calculate the XOR checksum of something (eg. NMEA 0183 GPS output), create a function such as:

import operator
def checksum(s):
    return reduce(operator.xor, [ord(c) for c in s])

It may not be as universally accepted as unrolling the whole statement, but it does wonders to reduce the overall size of your program - especially if you have tons of simple functions you need to pump out.

While this is less than groundbreaking, perhaps it will serve as an inspiration for a GPS tracking device or something. Sparkfun has some pretty cool GM632 modules that have a built in GPS and run Python.

Also, watch for an update sometime soon about the new pup :)

comments:
Post

Type the string below:

 ____  _             _____ 
| _ \| |____ _|___ /
| | | | '_ \ \ /\ / / |_ \
| |_| | |_) \ V V / ___) |
|____/|_.__/ \_/\_/ |____/

*Comments may take up to 60 seconds to appear.

swilly , 1 year ago
Well, reduce() seems to be removed in Python3k, so you have to be more verbose (which may not be such a bad thing for complex operations). Below is the modified code for NMEA 0183 checksums.

def checksum(s):
  csum = 0
  for c in s:
  csum^= ord(c)
  return csum

Reply

Type the string below:

 ____  _             _____ 
| _ \| |____ _|___ /
| | | | '_ \ \ /\ / / |_ \
| |_| | |_) \ V V / ___) |
|____/|_.__/ \_/\_/ |____/

*Comments may take up to 60 seconds to appear.