# Best way to make a weighted sum

Jorge Godoy godoy at metalab.unc.edu
Tue Apr 8 21:34:36 CEST 2003

Hi!

I have the following snippet of code:

----------------------------------------------------------------------
class IEModulo11:

def __init__(self, ie=None, uf=None):

self.ie = ie
self.soma = 0

def EstipulaPesos(self, uf=None):
"""
First digit indicates the number position, the second indicates
it's weight.
"""

if uf in ['CE', 'AP']:
self.pesos = {8:9, 7:8, 6:7, 5:6, 4:5, 3:4, 2:3, 1:2}
else:
if uf in ['RJ']:
self.pesos = {7:2, 6:7, 5:6, 4:5, 3:4, 2:3, 1:2}

def CalculaSoma(self):

ie = self.ie
iter = len(ie)

for i in ie:
produto = i * self.pesos[iter]
self.soma = self.soma + produto
iter = iter - 1

----------------------------------------------------------------------

What I want is to sum the products of a certain 'ie' number where each
of its digits is multiplied by a certain weigth, depending on its
position inside the number. (This is for some documents verification
and 'ie' can vary in the amount of digits as well as its weigth can
vary from one place to another --- I know this is a mess, but it's the
way some Brazilian states did it...)

I don't know if I got it in the most pythonic way in my code.

TIA,
--
Godoy.      <godoy at metalab.unc.edu>

Your analyst has you mixed up with another patient.  Don't believe a
thing he tells you.