I believe this will solve your problem:
# Using ternary operator to condense the print's
two_sum = lambda s, target: print('yes') if any(map(lambda x: target-x in s and s.count(x)>1, s)) else print('no')
# If s.count(x) is 1, it means the subtraction resulted in the same element took that time for the operation, which we don't want to happen. So the count must be greater then 1
two_sum([-8, 3, 5, 1, 3], -5)
# Output is "yes"
two_sum([2], 4)
# Output is "no"
So, we wrapped the function in a lambda, used another lambda in the map call and preserved all items in the list, checking if the output matches another element besides the one took in for the calculation.
Benchmark
I was wondering if @Juho's answer provided a faster function, so I benchmarked both.
So:
two_sum = lambda s, target: any(map(lambda x: target-x in s and s.count(x)>1, s))
is_2sum = lambda s, target: any(target - s[j] in s[j+1:len(s)] for j in range(len(s)))
# The print's aren't necessary for the benchmark.
Then, I ran both at Google Colab with the following code:
two_sum = lambda s, target: any(map(lambda x: target-x in s and s.count(x)>1, s))
is_2sum = lambda s, target: any(target - s[j] in s[j+1:len(s)] for j in range(len(s)))
test_function = two_sum
# test_function = is_2sum
if __name__ == "__main__":
import timeit
setup = "from __main__ import test_function"
average=0
for i in range(0,100):
average=average+timeit.timeit("test_function([-8, 3, 1, 5, 1, 3], -5)", setup=setup, number=1000000)
print(average/100)
The method timeit.timeit()
will run each function 1.000.000 times, then I record the outputs of 100 iterations (so, we actually ran the function 100.000.000 times) and take the average.
Results:
For the function two_sum
:
First run: 0.9409843384699957
Second run: 0.948360692339993
For the function is_2sum
:
First run: 0.9963176720300112
Second run: 0.998327726480004
As you can see, there is an increase in performance for two_sum
function, whether this comes from the use of map()
and avoiding lists operations, I don't know, but it's a bit faster.
target = 4
fors = [2]
which gives youyes
, did you describe the wrong case? Because your current approach will outputno
for that input case. \$\endgroup\$int(...)
conversions if the inputs are already integers? Is the function meant to also work with non-integer inputs? If so, is the rounding behaviour ofint
really what you want? \$\endgroup\$