Thursday, July 9, 2015

Python: list(1) hunt the sum of two numbers equal to a given number


Abstract: hunt the sum of two numbers equal to a given number

The result:
The length of the number pool is  500
The length of the final pool is  251
The equation of  1256  is  [[561, 695], [612, 644], [695, 561]]


The script:
# -*- coding: utf-8 -*-
"""
Created on Thu Jul  9 13:18:35 2015

@author: yuan
"""
import random

#hunt two numbers plus equal to a given number
class mylist:
   
    def __init__(self, number):
        #generate random numbers
        self.arr=[]
        for i in range(500):
            value=random.randint(1, 10000)
            self.arr.append(value)
        print 'The length of the number pool is ', len(self.arr)
        self.number=number
   
    def hunt_double_numbers(self):
        arr=list(self.arr)
        target=[]
        for a in arr:
            b=self.number - a
            if b in self.arr:
                target.append([a,b])
            else:
                arr.remove(a)
        #
        print 'The length of the final pool is ', len(arr)
        if len(target)==0:
            print 'not hunted numbers!'
        else:
            print 'The equation of ', self.number, ' is ', target

#main program
hunt=mylist(1256)
hunt.hunt_double_numbers()
       

       
       
   

No comments:

Post a Comment