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)?
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.
Step 1 : For i from 0 to n-1, follow step 2 ; Step 2 : sum = sum + arr[i] Step 3 : print sum.
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.
I am assuming you mean a list or maybe another kind of iterable:
sum(x.getNumber() for x in L)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With