Sq.(n) Sum in Python | Software program Enginering Authority


The problem

Full the sq. sum operate in order that it squares every quantity handed into it after which sums the outcomes collectively.

For instance, for [1, 2, 2] it ought to return 9 as a result of 1^2 + 2^2 + 2^2 = 9.

Full the sq. sum operate in order that it squares every quantity handed into it after which sums the outcomes collectively.

For instance, for [1, 2, 2] it ought to return 9 as a result of 1^2 + 2^2 + 2^2 = 9.

The answer in Python

Choice 1:

def square_sum(numbers):
    out = []
    for i in numbers:
        out.append(i**2)
    return sum(out)

Choice 2:

def square_sum(numbers):
    return sum(x ** 2 for x in numbers)

Choice 3:

def square_sum(numbers):
    return sum(map(lambda x: x**2,numbers))

Take a look at circumstances to validate our resolution

import take a look at
from resolution import square_sum

@take a look at.describe("Fastened Assessments")
def basic_tests():
    @take a look at.it('Primary Take a look at Instances')
    def basic_test_cases():
        take a look at.assert_equals(square_sum([1,2]), 5)
        take a look at.assert_equals(square_sum([0, 3, 4, 5]), 50)
        take a look at.assert_equals(square_sum([]), 0)
        take a look at.assert_equals(square_sum([-1,-2]), 5)
        take a look at.assert_equals(square_sum([-1,0,1]), 2)
See also  How you can Fold an Array in Java

Leave a Reply