Calculate the Sum of the Two Lowest Positive Integers in Python

  • Home /
  • Blog Posts /
  • 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])

Option 2:

def sum_two_smallest_numbers(num_list):
    num_list.sort()
    return num_list[0] + num_list[1]

Option 3:

sum_two_smallest_numbers = lambda A: sum( sorted( filter( lambda x:x>0, A) )[:2] )

Test cases to validate our solution

import test
from solution import sum_two_smallest_numbers

@test.describe("Fixed Tests")
def fixed_tests():
    @test.it('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)