Home > OS >  Codewars Python Two sum not working for some test cases
Codewars Python Two sum not working for some test cases

Time:01-29

This Python code is not working for some test cases on code wars two sum. Here is the link to the problem: https://www.codewars.com/kata/52c31f8e6605bcc646000082/train/python

def two_sum(nums, target):
    nums.sort()
    l = 0
    r = len(nums)-1
    while l < r:
        sum = nums[l]   nums[r]
        if sum == target:
            return [l, r]
        if sum > target:
            r -= 1
        if sum < target:
            l  = 1
    return []

Any help is much appreciated! :)

CodePudding user response:

The solution you are looking for will be:

def two_sum(nums, target):
    indices = {}
    for index, num in enumerate(nums):
        remainder = target - num
        if remainder in indices:
           return indices[remainder], index
        indices[num] = index
    return 0, 0

Right off the bat, I can also tell you that sorting nums before doing anything else is bad because the original indices can get mixed up.

CodePudding user response:

def two_sum(numbers, target):
    for n1 in enumerate(numbers):
        for n2 in enumerate(numbers):
            if n1[0] != n2[0]:
                if (n1[1]   n2[1]) == target:
                    return [n1[0], n2[0]]
  • Related