Yes I know this has no graceful error protection for user input, wanted the example code to focused on problem space.
#!/usr/bin/env python import random import sys X=int(sys.argv[1]) # e.g. enter 100 on the command line print "In list of numbers, find each pair that equals " + str(X) myNumbers = [] matched = [] for i in range(1,X): myNumbers.append(random.randrange(0,X)) for i in myNumbers: A=myNumbers.pop() for j in myNumbers: if A != False: try: if ((A+myNumbers[j]) == X): B=myNumbers[j] del myNumbers[j] matched.append([A, B]) A = False except: TypeError for i, j in enumerate(matched): if ((i>0) and (i % 5 == 0)): print j else: print j, print print "length of remaining unmatched numbers list is " + str(len(myNumbers)) print "length of remaining matched numbers list is " + str(len(matched))
No comments:
Post a Comment