Simple Array Sum

  • ar: an array of integers
6
1 2 3 4 10 11
31
def simpleArraySum(ar):“””Initialize sum to zeroNote:The variable name for the sum is my_sum and not sum.This is due to the fact that sum is a keyword that references an inbuilt python function which will pretty much do what were doing here but it’s important to understand the process.“””my_sum = 0“””We are going to iterate through the array to and add every value in the array to the current sum.Note:since the sum is initialized to zero the value of sum will just be the total of all the values in the array . Consider it the offset. Like you would if you were counting on a number line.“””for number in ar:“””The += operator is simply an augmented operator that equivalent to the summation of the value on the right side and the left side of the operator in simple terms. An example in this case it will translate to.my_sum = my_sum + number.“””my_sum += number“””simply return the sum after the iteration.To complete the challenge.“””return my_sum"""
time complexity = O(n)
space complexity = O(1)
"""
def simpleArraySum(ar):return sum(ar)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Munalula Sikazwe

Munalula Sikazwe

13 Followers

I’m a computer Scientist and Python Developer . My hobbies are playing chess and watching movies with convoluted storylines like Tenet or Inception.