Skip to main content
6 of 7
Rollback to Revision 2
Mathieu Guindon
  • 75.1k
  • 18
  • 191
  • 463

Checking the sum of pairs to match a target value

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
tyluRp
  • 163
  • 5