I'm new to Python and curious what looks good and what doesn't. The function I have defined looks for pairs in a list of integers and tells the user whether or not any possible pair equals the target number. How can this code be more efficient or fast?
import datetime
from itertools import combinations
def csop(*params):
t1 = datetime.datetime.now()
print params[0], params[1]
for c in combinations(params[0],2):
print sum(c)
if sum(c) == params[1]:
print 'Target number reached'
t2 = datetime.datetime.now()
print t2-t1
exit()
else:
pass
To run:
import csop
csop.csop([1,2,3,4],5)
The output should look something like this:
[1, 2, 3, 4] 5
3
4
5
Target number reached
0:00:00.000071
Modifications to code:
import datetime
from itertools import combinations
def csop(numbers, target_value):
t1 = datetime.datetime.now()
print numbers, target_value
for c in combinations(numbers,2):
if sum(c) == target_value:
print 'Target value reached'
t2 = datetime.datetime.now()
print t2-t1
return