Finding first pair of numbers in array that sum to

2020-04-11 11:55发布

Im trying to solve the following Codewars problem: https://www.codewars.com/kata/sum-of-pairs/train/python

Here is my current implementation in Python:

def sum_pairs(ints, s):
    right = float("inf")

    n = len(ints)
    m = {}
    dup = {}

    for i, x in enumerate(ints):
        if x not in m.keys():
            m[x] = i # Track first index of x using hash map. 
        elif x in m.keys() and x not in dup.keys():
            dup[x] = i

        for x in m.keys():
            if s - x in m.keys():
                if x == s-x and x in dup.keys():
                    j = m[x]
                    k = dup[x]
                else:
                    j = m[x]
                    k = m[s-x]


                comp = max(j,k)
                if comp < right and j!= k:
                    right = comp


    if right > n:
        return None

    return [s - ints[right],ints[right]]

The code seems to produce correct results, however the input can consist of array with up to 10 000 000 elements, so the execution times out for large inputs. I need help with optimizing/modifying the code so that it can handle sufficiently large arrays.

3条回答
迷人小祖宗
2楼-- · 2020-04-11 12:10

Your code inefficient for large list test cases so it gives timeout error. Instead you can do:

def sum_pairs(lst, s):
    seen = set()
    for item in lst:
        if s - item in seen:
            return [s - item, item]
        seen.add(item)

We put the values in seen until we find a value that produces the specified sum with one of the seen values. For more information go: Referance link

查看更多
一纸荒年 Trace。
3楼-- · 2020-04-11 12:12

Maybe this code:

def sum_pairs(lst, s):
    c = 0
    while c<len(lst)-1:
        if c != len(lst)-1: 
            x= lst[c]
            spam = c+1
            while spam < len(lst):
                nxt= lst[spam]
                if nxt + x== s:
                    return [x, nxt]
                spam += 1
        else:
            return None
        c +=1
lst = [5, 6, 5, 8]
s = 14
print(sum_pairs(lst, s)) 

Output:

[6, 8]
查看更多
我命由我不由天
4楼-- · 2020-04-11 12:30

This answer unfortunately still times out, even though it's supposed to run in O(n^3) (since it is dominated by the sort, the rest of the algorithm running in O(n)). I'm not sure how you can obtain better than this complexity, but I thought I might put this idea out there.

def sum_pairs(ints, s):
    ints_with_idx = enumerate(ints)

    # Sort the array of ints
    ints_with_idx = sorted(ints_with_idx, key = lambda (idx, num) : num)

    diff = 1000000
    l = 0
    r = len(ints) - 1

    # Indexes of the sum operands in sorted array
    lSum = 0
    rSum = 0

    while l < r:
        # Compute the absolute difference between the current sum and the desired sum
        sum = ints_with_idx[l][1] + ints_with_idx[r][1]
        absDiff = abs(sum - s)
        if absDiff < diff:
            # Update the best difference
            lSum = l
            rSum = r
            diff = absDiff
        elif sum > s:
            # Decrease the large value
            r -= 1
        else:
            # Test to see if the indexes are better (more to the left) for the same difference
            if absDiff == diff:
                rightmostIdx = max(ints_with_idx[l][0], ints_with_idx[r][0])
                if rightmostIdx < max(ints_with_idx[lSum][0], ints_with_idx[rSum][0]):
                    lSum = l
                    rSum = r
            # Increase the small value
            l += 1

    # Retrieve indexes of sum operands
    aSumIdx = ints_with_idx[lSum][0]
    bSumIdx = ints_with_idx[rSum][0]

    # Retrieve values of operands for sum in correct order
    aSum = ints[min(aSumIdx, bSumIdx)]
    bSum = ints[max(aSumIdx, bSumIdx)]

    if aSum + bSum == s:
        return [aSum, bSum]
    else:
        return None
查看更多
登录 后发表回答