[Tutor] please help!

Magnus Lycka magnus@thinkware.se
Fri Jan 10 07:06:34 2003


>geraldine lynch schrieb:
>>How do I sum all the elements of an array? ...

I'm assuming that "array" is a sequence (list or tuple)
of numbers of some kind...

"sum(array)" would seem like a reasonable approach,
right? That's what I would do. You would have to
define the sum function first, but that is fairly
trivial.

At 11:50 2003-01-10 +0100, Gregor Lingl wrote:
>you can use the builtin function reduce for this ...

But a more conventional solution would be

def sum(array):
     s = 0
     for element in array:
         s = s + element
     return s

Performance is roughly the same, and you don't need to introduce
any concepts that might be unknown to other programmers. Everybody
who has some basic understanding of Python understands those five
lines of code, and it reads more or less like English.

operator.add(1,2) is probably less obvious than 1 + 2, and
reduce, filter and map are confusing to many programmers.

"s = s + element" can be replaced with the shorter form
"s += element" if you prefer to type a little less...

A sum function is certainly a reasonable thing to have in one's
tool box. Like the builtins min and max, it might be a good thing
if it can also handle things like "sum(1,2,3)".

Let's see...

 >>> def sum(*args):
...     sum = 0
...     for arg in args:
...         if hasattr(arg, '__len__'):
...             for x in arg:
...                 sum += x
...         else:
...             sum += arg
...     return sum
...
 >>> sum(1,2,3)
6
 >>> sum([1,2,3])
6
 >>> sum([1,2,3],4,(5,6))
21

Notice that this doesn't work like the builtin min and max.
They won't treat the third case like our sum does. Also note
that while we can sum all elements of several sequences, we
won't follow structures further.

 >>> sum([1,2,3],4,(5, 6, (5,6)))
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 6, in sum
TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'



-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se