Skip to content

Calculate the Sum of the two lowest positive integers in Python

The challenge

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

[10, 343445353, 3453445, 3453545353453] should return 3453455.

The solution in Python code

Option 1:

def sum_two_smallest_numbers(numbers): return sum(sorted(numbers)[:2])
Code language: Python (python)

Option 2:

def sum_two_smallest_numbers(num_list): num_list.sort() return num_list[] + num_list[1]
Code language: Python (python)

Option 3:

sum_two_smallest_numbers = lambda A: sum( sorted( filter( lambda x:x>, A) )[:2] )
Code language: Python (python)

Test cases to validate our solution

import test from solution import sum_two_smallest_numbers @test.describe("Fixed Tests") def fixed_tests():'Basic Test Cases') def basic_test_cases(): test.assert_equals(sum_two_smallest_numbers([5, 8, 12, 18, 22]), 13) test.assert_equals(sum_two_smallest_numbers([7, 15, 12, 18, 22]), 19) test.assert_equals(sum_two_smallest_numbers([25, 42, 12, 18, 22]), 30)
Code language: Python (python)

See also  How to Fill an Array in Python
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x