ActiveState Code

Recipe 52251: simple string checksum


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
 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)

Comments

  1. 1. At 1:12 p.m. on 1 jun 2001, Jürgen Hermann said:

    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.

Sign in to comment