from typing import List
from typing import Tuple


def bounded_rectangle(
    rect: List[Tuple[float, float]], bounds: List[Tuple[float, float]]
) -> List[Tuple[float, float]]:
    """
    Resize rectangle given by points into a rectangle that fits within bounds, preserving the aspect ratio
    :param rect: Input rectangle [ll, ur], where each point is (y, x)
    :param bounds: Input bounding rectangle [ll, ur]
    :return: Bounded rectangle with same aspect ratio
    """
    assert len(rect) == len(bounds) == 2
    assert rect[0][0] <= rect[1][0] and rect[0][1] <= rect[1][1]
    assert bounds[0][0] <= bounds[1][0] and bounds[0][1] <= bounds[1][1]

    w_input = rect[1][1] - rect[0][1]
    h_input = rect[1][0] - rect[0][0]
    w_bound = bounds[1][1] - bounds[0][1]
    h_bound = bounds[1][0] - bounds[0][0]

    w = w_input
    h = h_input

    # find new rect points
    while w > w_bound or h > h_bound:

        if w > w_bound:
            # need to bound w
            a_w = w_bound / w
            w = w_bound
            h = h * a_w

        if h > h_bound:
            # need to bound w
            a_h = h_bound / h
            h = h_bound
            w = w * a_h

    rect_out = [rect[0], (rect[0][0] + h, rect[0][1] + w)]

    return rect_out