LeetCode in Python3 - Two Sum

As a graduate student in Statistics, I profoundly believe the power of programming skills to Statistics/ Data Science. I used R or Matlab as my default programming tools and they are pretty powerful to help me solve most mathematical related tasks. However I realize in Artificial Intelligence/ Machine Learning realm, Python is more prevelent. In order to better gain the gist of this mighty programming language, in the process of learning it, I will show my LeetCode practice in Python3 with relative explanations as well as pitfalls I encounter.

Question

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution

1
2
3
4
5
class Solution:
def twoSum(self, nums, target):
for i in range(len(nums)):
if (target - nums[i]) in nums[i+1:]:
return (i, nums.index(target - nums[i], i+1) )

Analysis

  • It is easily to ignore the condition “not use the same element twice” in the question. Initially I used
    return (i, nums.index(target - nums[i] ) instead of
    return (i, nums.index(target - nums[i], i+1 ),
    it works for most cases, but for example such as Given nums = [3,3], target = 6, it failed to give me [0,1], it returned [0,0]. So basically .index(A,B) is to find the position of A after Bth index.

  • Another point worthy of mentioning is self in the definition part def twoSum( self, nums, target). self is used to refer class in python. In this case the class is Solution

Difficulty

Easy

0%