Q:

How can I optimize my Two Sums code in Python?

I'm attempting the first problem on leetcode and my code passes the first 19 tests but fails due to a time exceeded failure on the last test. This is what I have so far:
class Solution:
    def twoSum(self, nums, target):
        k = 0
        n = len(nums)-1
        temp = []
        for x in range(k,n):
            for y in range(k+1,n+1):
                if (nums[x]+nums[y] == target) and (x < y):
                    temp.append(x)
                    temp.append(y)
                    break
        return temp

Please let me know if you have any information that you think could potentially help me. 
For those of you unfamiliar with the two sums problem. Here it is:
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]

I'm asking about the specifics about how to optimize MY code, not have other people write the code for me. Afterall, memorizing code won't do me any good if I don't know how to do it myself with my own thought processes. I'm asking for advice.

A:

You can probably speed things up a little bit using itertools, e.g.:
for i, j in it.combinations(range(len(nums)), r=2):
    if nums[i] + nums[j] == target:
        return [i, j]

Or alternatively:
for (i, x), (j, y) in it.combinations(enumerate(nums), r=2):
    if x+y == target:
        return [i, j]

An improvement to your code is in your second loop, to start from x+1 vs k+1, this removes the need for the and expression. And just immediately return vs. .append() which is relatively expensive. E.g.:
n = len(nums)-1
for x in range(0, n):
    for y in range(x+1, n+1):
        if nums[x]+nums[y] == target:
            return [x, y]

Loops in this structure is exactly what itertools.combinations() does.

