How to print multiple indexes from a list with brackets around it?

Viewed 41

I am trying to solve a simple leetcode problem, and my code can output the right answer but not in the correct format. Here is my code:

class Solution:

    def twoSum(self, nums: List[int], target: int) -> List[int]:
        list2 = []
        for x in nums:
            for y in nums:
                if x + y == target:
                    list2.append(x)
                    print(nums.index(x))

For the input of:

[2,7,11,15]
9

My code is outputting

0
1

When it should be outputting

[0,1]
1 Answers

Instead of printing the index, save it

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        list2 = []
        for x in nums:
            for y in nums:
                if x + y == target:
                    list2.append(nums.index(x))
        return list2

print(Solution().twoSum([2, 7, 11, 15], 9))  # [0, 1]

But instead of iterating the second, just look for the possible complement to the target

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        list2 = []
        for x in nums:
            possible_y = target - x
            if possible_y in nums:
                list2.append(nums.index(x))
        return list2
Related