0

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
3
  • Welcome to Stack Overflow. What happens with [3, 3]? Commented May 3, 2022 at 0:57
  • Passing [3,3] as a List serves as an input. The output is an empty list. "[]" Commented May 3, 2022 at 1:02
  • 1
    The answer to "are any of the lines below necessary?" is no. :) You'll never reach the return, and without that you'll just continue the loop regardless of the else. Commented May 3, 2022 at 1:03

1 Answer 1

2

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]) 
Sign up to request clarification or add additional context in comments.

1 Comment

I appreciate the help everyone, thank you for the swift answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.