# Andrew's monotone chain — Algo.pw
# Step through the construction: https://a...content-available-to-author-only...o.pw/convex-hull#lang=python3

def turn(a, b, c):
    return (b[0]-a[0])*(c[1]-a[1]) - (b[1]-a[1])*(c[0]-a[0])

def chain(points):
    edge = []
    for p in points:
        while len(edge) >= 2 and turn(edge[-2], edge[-1], p) <= 0:
            edge.pop()
        edge.append(p)
    return edge

def convex_hull(points):
    ordered = sorted((x,y) for x,y in points)
    pts = list(dict.fromkeys(ordered))
    if len(pts) <= 1:
        return pts
    lower = chain(pts)
    upper = chain(reversed(pts))
    return lower[:-1] + upper[:-1]

# A square, with an interior point, a point on one side and a repeated corner.
points = [(0, 0), (2, 0), (2, 2), (0, 2), (1, 1), (1, 0), (0, 0)]
print(convex_hull(points))
