Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum numbers in an array

Tags:

python-3.x

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

like image 516
sivabudh Avatar asked Sep 10 '10 21:09

sivabudh


People also ask

How do you sum numbers in JavaScript?

const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.

How do you sum an array in C++?

Step 1 : For i from 0 to n-1, follow step 2 ; Step 2 : sum = sum + arr[i] Step 3 : print sum.

How do you calculate and return the sum of the numbers in an array in JavaScript?

To get the sum of an array of numbers: Use the Array. reduce() method to iterate over the array. Set the initial value in the reduce method to 0 . On each iteration, return the sum of the accumulated value and the current number.


1 Answers

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

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

like image 105
supakeen Avatar answered Oct 06 '22 14:10

supakeen