In this series of posts, I will attempt to explain how to solve the daily coding problems sent out by dailycodingproblem.com
This problem was recently asked by Google.
Given a list of numbers and a number
k, return whether any two numbers from the list add up to
For example, given
[10, 15, 3, 7]and
17, return true since
10 + 7is
# returns a list with two numbers that add up to k (if two numbers that add up to k can be found) # returns an empty list otherwise def AnyTwoInListAddUpToK(numbers, k): retval =  for index1 in range(len(numbers)): for index2 in range(index1, len(numbers)): if (numbers[index1] + numbers[index2] == k): retval.append(numbers[index1]) retval.append(numbers[index2]) return retval numbers = [10, 15, 3, 7] k = 17 result = AnyTwoInListAddUpToK(numbers, k) if len(result) == 0: print("no dice") else: print("%d and %d add up to %d" % (result, result, k))
Here is my solution quickly implemented in Python. (Not too much to explain, as the solution is pretty straight-forward.)
But getting an easy problem like this right off the bat is good because it will help me get started with the habit of solving the problems everyday.
To make it more challenging, I will try to solve them using different (and sometimes exotic) programming languages.