Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function called sumAndAverage. It should take in an array of numbers and

ID: 3670936 • Letter: W

Question

Write a function called sumAndAverage. It should take in an array of numbers and return the sum and average of the array in that order. For example:

[s a] = sumAndAverage([3 2 3 2]) %should return 10 and 2.5

[s a] = sumAndAverage([5 -5 2 8 0]) %should return 10 and 2

[s a] = sumAndAverage([]) %should return 0 and 0

You can use Built-in functions.

Create a vector, then invoke your function like this:

>>Arr=[3 2 3 2]

>>[s a]=sumAndAverage(Arr)

Note: the function has only one parameter. It is a vector

Explanation / Answer

def sumAndAverage(arr):
    if len(arr) == 0:
        return [0,0]

    return [sum(arr), sum(arr)*1.0/len(arr)]


Arr = [3, 2, 3, 2]
[s, a] = sumAndAverage(Arr)
print "Sum = "+str(s)
print "Average = "+str(a)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote