Welcome, guest | Sign In | My Account | Store | Cart

This one line function adds up the ascii values of a string and returns the total as a checksum. Also included is a variation which returns the checksum mod 256 (so it can be used as a single byte). The same technique can be used to add up a list of numbers, or to return the average of a list (examples are also included) or to do any other any other simple processing on a list or a string.

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# returns total as checksum
# input - string
def checksum(st):
    return reduce(lambda x,y:x+y, map(ord, st))

# returns total mod 256 as checksum
# input - string
def checksum256(st):
    return reduce(lambda x,y:x+y, map(ord, st)) % 256

# totals a list of numbers
# input - list or tuple of numbers
def totalList(lst):
    return reduce(lambda x,y:x+y, lst)

# returns the average of a list of numbers
# input - list or tuple of numbers
def averageList(lst):
    return reduce(lambda x,y:x+y, lst) / len(lst)

2 comments

J├╝rgen Hermann 20 years, 6 months ago  # | flag

Use builtin over lambda whenever possible. Use "operator.add" instead of "lambda x,y:x+y" which avoids the overhead of "n" Python function calls.

Michael W. Losinski 11 years, 7 months ago  # | flag

Doesn't a typical checksum use a xor not addition? I.E. x + y => x ^ y

Created by Yosef Gold on Wed, 14 Mar 2001 (PSF)
Python recipes (4591)
Yosef Gold's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks