>>> a = LineSegment(Point(1,0), Point(2,0))
    >>> b = LineSegment(Point(2,0), Point(0,2))
    >>> point_segment_distance(Point(0,0), a)
    1.0
    >>> "%0.2f" % point_segment_distance(Point(0,0), b)
    '1.41'

def point_segment_distance(point, segment):
    """
    >>> a = LineSegment(Point(1,0), Point(2,0))
    >>> b = LineSegment(Point(2,0), Point(0,2))
    >>> point_segment_distance(Point(0,0), a)
    1.0
    >>> "%0.2f" % point_segment_distance(Point(0,0), b)
    '1.41'
    """
    assert isinstance(point, Point), \
        "point is not of type Point, but of %r" % type(point)
    dx = segment.p2.x - segment.p1.x
    dy = segment.p2.y - segment.p1.y
    if dx == dy == 0:  # the segment's just a point
        return point.dist_to(segment.p1)

    if dx == 0:  # It's a straight vertical line
        p_below_p1 = point.y <= segment.p1.y and segment.p1.y <= segment.p2.y
        p_below_p2 = point.y <= segment.p2.y and segment.p2.y <= segment.p1.y
        p_above_p2 = segment.p1.y <= segment.p2.y and segment.p2.y <= point.y
        p_above_p1 = segment.p2.y <= segment.p1.y and segment.p1.y <= point.y
        if p_below_p1 or p_above_p1:
            return point.dist_to(segment.p1)
        elif p_below_p2 or p_above_p2:
            return point.dist_to(segment.p2)

    if dy == 0:  # It's a straight horizontal line
        p_left_p1 = point.x <= segment.p1.x and segment.p1.x <= segment.p2.x
        p_left_p2 = point.x <= segment.p2.x and segment.p2.x <= segment.p1.x
        p_right_p2 = segment.p1.x <= segment.p2.x and segment.p2.x <= point.x
        p_right_p1 = segment.p2.x <= segment.p1.x and segment.p1.x <= point.x
        if p_left_p1 or p_right_p1:
            return point.dist_to(segment.p1)
        elif p_left_p2 or p_right_p2:
            return point.dist_to(segment.p2)

    # Calculate the t that minimizes the distance.
    t = ((point.x - segment.p1.x) * dx + (point.y - segment.p1.y) * dy) / \
        (dx * dx + dy * dy)

    # See if this represents one of the segment's
    # end points or a point in the middle.
    if t < 0:
        dx = point.x - segment.p1.x
        dy = point.y - segment.p1.y
    elif t > 1:
        dx = point.x - segment.p2.x
        dy = point.y - segment.p2.y
    else:
        near_x = segment.p1.x + t * dx
        near_y = segment.p1.y + t * dy
        dx = point.x - near_x
        dy = point.y - near_y
    return math.hypot(dx, dy)