tags:

views:

210

answers:

4

I'm a Python newbie.

At this site, they show how to sum list of integers.

What if instead of a list of raw ints, you had a list of

class Number :
   def __init__( self, x = 0) :
      self.number = x      

   def getNumber( self ) :
      return self.number

What's the Python code to sum the self.number in an array in a few lines (hopefully)?

+2  A: 

Try this:

sum(x.getNumber() for x in l)

By the way, [1, 2, 3]is a list, not an array.

Mark Byers
+1  A: 

Use a generator or list comprehension:

numbers = [Number(1), Number(2)]
sum(n.getNumber() for n in numbers)

Simply, it calls the method getNumber() on each item before summing.

Sanjay Manohar
+3  A: 

I am assuming you mean a list or maybe another kind of iterable:

sum(x.getNumber() for x in L)

ikanobori
A: 

Here are several ways to do it:

sum( e.getNumber() for e in L )

sum( e.number for e in L )

reduce( lambda a,b: a + b.getNumber(), L, 0 )  # likewise for e.number
OTZ
@OTZ, geez, thanks for the attitude. But I will thank you anyway for showing me a few different ways to solve the problem.
ShaChris23
hold on, should the last one not be `lambda x,e: x+e.getNumber(),L,0` ?
Sanjay Manohar
@OTZ, what if it's python 3.0, can we use something else instead of reduce()? See: http://www.artima.com/weblogs/viewpost.jsp?thread=98196
ShaChris23
@ShaChris23 We still have reduce in Python 3, but is in functools module. So use `functools.reduce()` instead. But knowing the `reduce` concept is still nice. It is somewhat (but not totally) related to `MapReduce`, which you are supposed to know if you are a software engineer.
OTZ
Adding a positive vote since the sarcasm has already been removed, to be fair to you. Still your lowest-scoring answer though :P
BoltClock