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]
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]
may be you try it:
if self.nums[i] + self.nums[j] == target:
# ^^^^^ ^^^^^
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)
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) => []
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.