0

This is an exercise on LeetCode. I get an except of

UnboundLocalError on line 15.

Why? And how to fix it?

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        self.nums = []
        self.target = int

        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    a = []
                return a[i, j]
1
  • Please either attach the problem statement or add the problem link with this type of post. Commented Feb 7, 2021 at 4:07

5 Answers 5

3

I believe this would work:

class Solution:
def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    n = len(nums)
    for i in range(n):
        for j in  range(i+1, n):
            if nums[i] + nums[j] == target:
                return [i,j]
Sign up to request clarification or add additional context in comments.

Comments

1
class Solution:
   def twoSum(self, nums, target):
   """
   :type nums: List[int]
   :type target: int
   :rtype: List[int]
   """
   n = len(nums)
   for i in range(n):
      for j in  range(i+1, n):
         if nums[i] + nums[j] == target:
            return [i,j]

Comments

0

may be you try it:

if self.nums[i] + self.nums[j] == target:
#  ^^^^^          ^^^^^

Comments

0

Let's examine your code:

First scenario (No combination matches target)

The method returns a value which is not yet defined:

return a[i, j]

But a was never defined!

Second scenario (Combination matches target)

The method returns a value which was initialized:

a = []

But, we never set the value at index [i, j], so this still won't work:

return a[i, j]

Solution

When you find a combination that equals the target, return their indices:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        self.nums = []
        self.target = int

        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return i, j

if __name__ == "__main__":
    a = Solution()
    print a.twoSum([1,2,3,4,5], 5)

Comments

0

See if this helps... return all possible indices:

def getIndices(tlist, target):
    return [(tlist.index(i), tlist.index(j)) for x,i in enumerate(tlist) for j in tlist[x:] if i!=j and i+j==target]

How to call:

getIndices(<your-list>, <your-target>)

Examples:

getIndices([1,2,3,4,5,6,7,8], 10) => [(1, 7), (2, 6), (3, 5)]
getIndices([1,2,3,4,5,6,7,8], 100) => []

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.