Best way to make a weighted sum

Steven Taschuk staschuk at telusplanet.net
Wed Apr 9 03:47:55 CEST 2003

```Quoth Jorge Godoy:
> Steven Taschuk <staschuk at telusplanet.net> writes:
>
> > I don't know why you're using a class for this.  A simple function
> > which calculates (and/or verifies) the checksum seems more natural.
>
> The class has several other things. As I said, this was a snippet of
> code. It showed you the __init__ and the other methods I was
> interested in discussing.

Ah.  Sorry, I thought you posted the complete class.  My mistake.

[...]
> The line that does the mod 11 is this one, in case you want to see it:
>
>         self.modulo = self.soma % 11
>
> Note that self.soma had other operations before being submitted
> here. Some of our States do really weird things before the modulus
> calculation. And some do these weird stuff after that.

Hm.  Another alternative, then: a dict mapping from state to
checksum function.  For the simple cases in your original message,
something like this:

checksumfuncs = {}

def simplechecksum(ie, weights):
w = weights[-len(ie):]
return reduce(operator.add, [x*y for x, y in zip(ie, w)]) % 11

checksumfuncs['CE'] = checksumfuncs['AP'] = \
lambda ie: simplechecksum(ie, [9, 8, 7, 6, 5, 4, 3, 2])
checksumfuncs['RJ'] = \
lambda ie: simplechecksum(ie, [2, 7, 6, 5, 4, 3, 2])

A weird checksum function might look like, for example,

def weirdchecksum(ie):
s = simplechecksum(ie, [2, 7, 6, 5, 4, 3, 2])
# do something weird to s
return s
checksumfuncs['AB'] = weirdchecksum

In this approach you might have

def checksum(ie, state):
return checksumfuncs[state](ie)

This might adapt better to the cases in which one state has many
ways of computing a checksum; the function for that state chooses
among the various methods by whatever means are appropriate.  (I
assume it's possible to determine the appropriate method by
inspecting ie.)

> > If uf is not in ['CE', 'AP', 'RJ'], then self.pesos simply does not
> > get set; this will cause CalculaSoma to fail later, in a mysterious
> > way.  Better to have an informative exception raised at this point,
> > surely.
[...]
> Also there will be no exception since this is also bound to a domain
> at the database server.

If it were my program, I'd check anyway, just in case.  At the
least I'd use an assertion.

> You enlightened me a lot on this message, thanks.

Glad I could be of help.

> There is a green, multi-legged creature crawling on your shoulder.

Aaah!

--
Steven Taschuk                                        staschuk at telusplanet.net
"Study this book; read a word then ponder on it.  If you interpret the meaning
loosely you will mistake the Way."         -- Musashi, _A Book of Five Rings_

```