Algorithm to find 100 closest stars to the origin

后端 未结 5 722
花落未央
花落未央 2021-01-31 11:34

First let me phrase the proper question:

Q: There is a file containing more than a million points (x,y) each of which represents a star. There is a planet earth

5条回答
  •  终归单人心
    2021-01-31 12:30

    import sys,os,csv
    
    iFile=open('./file_copd.out','rU')
    earth = [0,0]
    
    
    
    ##getDistance return distance given two stars
    def getDistance(star1,star2):
        return sqrt((star1[0]-star2[0])**2 +(star1[1]-star2[1])**2 )
    
    
    ##diction dict_galaxy looks like this  {key,distance}  key is the seq assign to each star, value is a list [distance,its cordinance]
    ##{1,[distance1,[x,y]];2,[distance2,[x,y]]}
    dict_galaxy={}
    #list_galaxy=[]
    count = 0
    sour=iFile.readlines()
    for line in sour:
        star=line.split(',')   ##Star is a list [x,y]
        dict_galaxy[count]=[getDistance(earth,star),star]
        count++
    
    ###Now sort this dictionary based on their distance, and return you a list of keys.
    list_sorted_key = sorted(dict_galaxy,key=lambda x:dict_galaxy[x][0])
    
    print 'is this what you want %s'%(list_sorted_key[:100].to_s)
    iFile.close()
    

提交回复
热议问题