How to find all ordered pairs of elements in array of integers whose sum lies in a given range of value

前端 未结 8 1190
抹茶落季
抹茶落季 2021-02-05 21:58

Given an array of integers find the number of all ordered pairs of elements in the array whose sum lies in a given range [a,b]

Here is an O(n^2) solution for the same <

8条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 22:11

    from itertools import ifilter, combinations
    
    def countpairs2(array, a, b):
        pairInRange = lambda x: sum(x) >= a and sum(x) <= b
        filtered = ifilter(pairInRange, combinations(array, 2))
        return sum([2 for x in filtered])
    

    I think the Itertools library comes in quite handy. I also noticed you counted pairs twice, for example you counted (1, 3) and (3, 1) as two different combinations. If you don't want that, just change the 2 in the last line to a 1. Note: The last could be changed to return len(list(filtered)) * 2. This CAN be faster, but at the expense of using more RAM.

提交回复
热议问题