[Tutor] please help!
Don Arnold
Don Arnold" <darnold02@sprynet.com
Sat Jan 11 11:41:29 2003
----- Original Message -----
From: "Magnus Lycka" <magnus@thinkware.se>
To: "Gregor Lingl" <glingl@aon.at>; "geraldine lynch"
<gerilynch@yahoo.co.uk>
Cc: <tutor@python.org>
Sent: Friday, January 10, 2003 6:10 AM
Subject: Re: [Tutor] please help!
>
> >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.
>
But with just a little recursion, we can sum nested lists that are nested
arbitrarilly deep:
>>> def sum(*args):
total = 0
for arg in args:
print 'summing', arg
if type(arg) in (list,tuple):
for item in arg:
total += sum(item)
else:
total += arg
return total
>>> sum(1,(2,(3,[4,8],(5,6)),7))
summing 1
summing (2, (3, [4, 8], (5, 6)), 7)
summing 2
summing (3, [4, 8], (5, 6))
summing 3
summing [4, 8]
summing 4
summing 8
summing (5, 6)
summing 5
summing 6
summing 7
36
Don