Sorting according to clockwise point coordinates

  • A+
Category:Languages

Given a list in Python containing 8 x, y coordinate values (all positive) of 4 points as [x1, x2, x3, x4, y1, y2, y3, y4] ((xi, yi) are x and y coordinates of ith point ),

How can I sort it such that new list [a1, a2, a3, a4, b1, b2, b3, b4] is such that coordinates (ai, bi) of 1 2 3 4 are clockwise in order with 1 closest to origin of xy plane, i.e. something like

          2--------3           |        |           |        |           |        |           1--------4 

Points will roughly form a parallelogram.

Currently, I am thinking of finding point with least value of (x+y) as 1, then 2 by the point with least x in remaining coordinates, 3 by largest value of (x + y) and 4 as the remaining point

 


# P4=8,10 P1=3,5   P2=8,5   P3=3,10 points=[8,3,8,3,10,5,5,10] k=0 #we know these numbers are extreme and data won't be bigger than these xmin=1000 xmax=-1000 ymin=1000 ymax=-1000 #finding min and max values of x and y for i in points:     if  k<4:         if (xmin>i): xmin=i         if (xmax<i): xmax=i             else:         if (ymin>i): ymin=i         if (ymax<i): ymax=i             k +=1  sortedlist=[xmin,xmin,xmax,xmax,ymin,ymax,ymax,ymin] print(sortedlist) 

output:[3, 3, 8, 8, 5, 10, 10, 5] for other regions you need to change sortedlist line. if center is inside the box then it will require more condition controlling

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: