So I've been attempting to solve the 3SUM problem and the following is my algorithm
def findThree(seq, goal):
for x in range(len(seq)-1):
left = x+1
right = len(seq)-1
while (left < right):
tmp = seq[left] + seq[right] + seq[x]
if tmp > goal:
right -= 1
elif tmp < goal:
left += 1
else:
return [seq[left],seq[right],seq[x]]
As you can see it's a really generic algorithm that solves it in O(n2).
The problem I've been experiencing is that this algorithm doesn't seem to like working with floating point numbers.
To test that my theory is right, I gave it the following two array
FloatingArr = [89.95, 120.0, 140.0, 179.95, 199.95, 259.95, 259.95, 259.95, 320.0, 320.0]
IntArr = [89, 120, 140, 179, 199, 259, 259, 259, 320, 320]
findThree(FloatingArr, 779.85) // I want it to return [259.95, 259.95, 259,95]
>> None // Fail
findThree(FloatingArr, 777) // I want it to return [259,259,259]
>> [259, 259, 259] // Success
The algorithm does work, but it doesn't seem to work well with floating point numbers. What can I do to fix this?
For additional information, my first array is originally a list of string of prices, but in order to do math with them, I had to strip the "$" sign off. My approach in doing so is this
for x in range(len(prices)):
prices[x] = float(prices[x][1:]) // return all the prices without the "$" sign. Casting them to float.
If there is a much better way, please let me know. I feel as if this problem is not really about findThree() but rather how I modified the original prices array.
Edit: Seeing that it is indeed a floating point problem, I guess my next question would be what is the best way to convert a string to int after I strip off the "$" ?