Square(n) Sum in Python

The challenge

Complete the square sum function so that it squares each number passed into it and then sums the results together.

For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9.

Complete the square sum function so that it squares each number passed into it and then sums the results together.

For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9.

The solution in Python

Option 1:

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

Option 2:

def square_sum(numbers): return sum(x ** 2 for x in numbers)
Code language: Python (python)

Option 3:

def square_sum(numbers): return sum(map(lambda x: x**2,numbers))
Code language: Python (python)

Test cases to validate our solution

import test from solution import square_sum @test.describe("Fixed Tests") def basic_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(square_sum([1,2]), 5) test.assert_equals(square_sum([0, 3, 4, 5]), 50) test.assert_equals(square_sum([]), 0) test.assert_equals(square_sum([-1,-2]), 5) test.assert_equals(square_sum([-1,0,1]), 2)
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments