fork download
  1. # Andrew's monotone chain — Algo.pw
  2. # Step through the construction: https://a...content-available-to-author-only...o.pw/convex-hull#lang=python3
  3.  
  4. def turn(a, b, c):
  5. return (b[0]-a[0])*(c[1]-a[1]) - (b[1]-a[1])*(c[0]-a[0])
  6.  
  7. def chain(points):
  8. edge = []
  9. for p in points:
  10. while len(edge) >= 2 and turn(edge[-2], edge[-1], p) <= 0:
  11. edge.pop()
  12. edge.append(p)
  13. return edge
  14.  
  15. def convex_hull(points):
  16. ordered = sorted((x,y) for x,y in points)
  17. pts = list(dict.fromkeys(ordered))
  18. if len(pts) <= 1:
  19. return pts
  20. lower = chain(pts)
  21. upper = chain(reversed(pts))
  22. return lower[:-1] + upper[:-1]
  23.  
  24. # A square, with an interior point, a point on one side and a repeated corner.
  25. points = [(0, 0), (2, 0), (2, 2), (0, 2), (1, 1), (1, 0), (0, 0)]
  26. print(convex_hull(points))
  27.  
Success #stdin #stdout 0.03s 5060KB
stdin
Standard input is empty
stdout
[(0, 0), (2, 0), (2, 2), (0, 2)]