5

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)?

sivabudh
  • 30,701
  • 59
  • 159
  • 223

4 Answers4

6

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

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

supakeen
  • 2,788
  • 17
  • 18
2

Try this:

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

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

Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
1

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
  • 6,731
  • 3
  • 34
  • 57
-1

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
  • 2,883
  • 4
  • 26
  • 40
  • geez, thanks for the attitude. But I will thank you anyway for showing me a few different ways to solve the problem. – sivabudh Sep 10 '10 at 21:59
  • hold on, should the last one not be `lambda x,e: x+e.getNumber(),L,0` ? – Sanjay Manohar Sep 10 '10 at 22:02
  • 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 – sivabudh Sep 10 '10 at 22:03
  • @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 Sep 10 '10 at 23:13
  • Adding a positive vote since the sarcasm has already been removed, to be fair to you. Still your lowest-scoring answer though :P – BoltClock Oct 07 '10 at 01:25