Question 6: Given a sorted array and a number x, find the pair in array whose sum is closest to or same as x
Examples:
Input: [2, 10, 22, 28, 29, 30, 40,51], x = 54
Output: 2 and 51
Input: [1, 3, 5, 7, 10], x = 15
Output: 5 and 10
Examples:
Input: [2, 10, 22, 28, 29, 30, 40,51], x = 54
Output: 2 and 51
Input: [1, 3, 5, 7, 10], x = 15
Output: 5 and 10
from itertools import combinations
ReplyDelete#sorted_array = [1, 3, 5, 7, 10]
#x = 15
sorted_array = [2, 22, 28, 29, 30, 51]
x = 54
pair_array = list(filter(lambda v: sum(v) <= x, list(combinations(sorted_array, 2))))
sorted_pair = sorted(pair_array, key=lambda x: sum(x))[-1]
print('%s and %s'%(sorted_pair[0], sorted_pair[1]))
Nice logic!! good use of existing modules!!!
ReplyDeleteThis comment has been removed by the author.
ReplyDelete