Enumerate is your friend :)


  • 0
    C

    I originally started with for loops then remembered about the enumerate function which produces very readable code.

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            
            for i, num in enumerate(nums, start=0):
                for i2, num2 in enumerate(nums[i:], start=i):
                    if i != i2:
                        if num + num2 == target:
                            return (i, i2)
    

    s = Solution()

    #print(s.twoSum([3,2,4], 6))
    #print(s.twoSum([-1,-2,-3,-4,-5], -8))
    #print(s.twoSum([2,7,11,15], 9))


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.