Can I get better answer?

def inNumAdd(array, n):
for i in range(len(array)):
for j in range(len(array)):
if int(array[i]) + int(array[j]) == k:
return True
return False
num_arr = input()
num_arr = num_arr.replace("[", “”).replace("]","").replace(" “, “”)
num_arr = num_arr.split(”,")
k = int(input())
print(inNumAdd(num_arr, k))

I wrote the code like this in response to the above question,

Can I get a better answer than O(n^2)?

The inner loop (the one using j) doesn’t need to iterate over the whole array. In fact doing that might give you a wrong answer, e.g. if 12 was part of the number list. Instead you should start j at i + 1. That way you avoid both adding elements to themselves and duplicate additions, e.g. if i is 2 you don’t need to consider j being 1, because you already added the same numbers when i was 1.

Two other things:

  • When posting code please enclose it in triple backticks (```). Most importantly that will preserve the spaces in your code, which are very important to understanding it. You can also add the programming language name after the backticks at the beginning to get nice syntax highlighting.
  • You could simplify the input code a bit by using command line arguments (sys.argv) instead of parsing an array written into input(), or by requiring the numbers to be separated by spaces instead of replicating Python array syntax.

Also try sorting the array. If any element of the array exceeds the target value, you can short-circuit the pass.


Good idea, but only true if all the numbers in the array are positive.