best cumulative sum

bonono at gmail.com bonono at gmail.com
Tue Nov 22 10:57:23 CET 2005


David Isaac wrote:
> <bonono at gmail.com> wrote in message
> news:1132553397.042444.147660 at g44g2000cwa.googlegroups.com...
> > He seems to want scanl
>
> Yes.  But it's not in Python, right?
> (I know about Keller's version.)
>
> Robert Kern wrote:
> > Define better. More accurate? Less code?
>
> Good point.
> As Bonono (?) suggested: I'd most like a solution that
> relies on a built-in to give me both of those.
> (Pretty is good too.)  Like SciPy's cumsum.
>
What is wrong with Keller's version ? I did write my own scanl/scanl1
using yield so it is a bit lazier than Keller's.

You can also use a Ref/Adder class. something like this :

class Adder:
  def __init__(self, i):
     self.val = i
  def add(self,i):
     self.val += i
     return self

a=Adder(init)
cl = [a.add(x).val for x in list]

But this I believe is against the idiom of the language as l.sort()
returns None rather than 'l', the preference that object method with
side effect(in this case add) should return None.

And it is debatable whether "add" should return self.val or self(even
one doesn't return None). As both has their use.

b = a.add(10) + 10

But then it may be violating some other idioms in the language.




More information about the Python-list mailing list