Saturday, September 30, 2023
HomeSoftware EngineeringLargest Pair Sum in Array in Python

Largest Pair Sum in Array in Python


The problem

Given a sequence of numbers, discover the most important pair sum within the sequence.

For instance

[10, 14, 2, 23, 19] -->  42 (= 23 + 19)
[99, 2, 2, 23, 19]  --> 122 (= 99 + 23)

Enter sequence accommodates minimal two parts and each factor is an integer.

The answer in Python code

Choice 1:

def largest_pair_sum(numbers):
    return sum(sorted(numbers)[-2:])

Choice 2:

def largest_pair_sum(numbers):
    max1 = max(numbers)
    numbers.take away(max1)
    max2 = max(numbers)
    return max1 + max2

Choice 3:

def largest_pair_sum(num):
    return num.pop(num.index(max(num))) + max(num)

Check circumstances to validate our answer

import check
from answer import largest_pair_sum

@check.describe("Mounted Assessments")
def fixed_tests():
    @check.it('Fundamental Check Instances')
    def basic_test_cases():
        check.assert_equals(largest_pair_sum([10,14,2,23,19]), 42)
        check.assert_equals(largest_pair_sum([-100,-29,-24,-19,19]), 0)
        check.assert_equals(largest_pair_sum([1,2,3,4,6,-1,2]), 10)
        check.assert_equals(largest_pair_sum([-10, -8, -16, -18, -19]), -18)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments