'Python can print but cannot return statement
New user, please go easy on me. Currently attempting leetcode twosum example and cannot return a statement. Oddly it prints when swapped out to the print keyword. The input example is [3,3] and should return [1,0] or [0,1] when the statement is returned. Looking at other questions on S/O it has to do with the subcall returning to the original loop but i still don't fully understand. Any tips?
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
self.nums = nums
self.target = target
nums = tuple(nums) #issue happens as a tuple and list.
for x in nums:
for y in nums:
if (x+y) == target:
#print ([x,y])
if (nums.index(x)!=nums.index(y) ):
return([nums.index(x), nums.index(y)]) #this statement will normally print
# are any of the lines below necessary?
else:
continue
return
Solution 1:[1]
Because the values are the same, nums.index(3) will always equal nums.index(3) since it will always find the first 3. To fix this, use enumerate to track the indices separately:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i, x in enumerate(nums):
for j, y in enumerate(nums):
if (x+y) == target:
if i != j:
return([i, j])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | C.Nivs |
