We're a place where coders share, stay up-to-date and grow their careers.

One pass in Python using built-in list and set types

def sum_exists(l,k): s = set() for x in l: if k-x in s: return True s.add(x) return False

Can I suggest you use more explicit variable names?

def sum_exists(numbers, target): numbers_seen = set() for number in numbers: if target - number in numbers_seen: return True numbers_seen.add(number) return False

Although I prefer a more concise implementation, although probably not O(N)

def sum_exists(numbers, target): differences = {target - number for number in numbers} return bool(differences.intersection(numbers))

This is should be the shortest version of your code

def sum_exists(ns, t): return bool({t - n for n in ns} & set(ns))

I've just realised that my algorithm is wrong, it would fail for something like 10 and [5]. Guess I need to put a bit more thought in my comments.

One pass in Python using built-in list and set types

Can I suggest you use more explicit variable names?

Although I prefer a more concise implementation, although probably not O(N)

This is should be the shortest version of your code

I've just realised that my algorithm is wrong, it would fail for something like 10 and [5]. Guess I need to put a bit more thought in my comments.