import random


def flip(img, p=1.0):
    """Flips image horizontally.

    Args:
        img (numpy.array): RGB or grayscale image.
        p (float): probability of flipping.

    Returns:
        img (numpy.array): flipped image.
    """
    if random.random() < p:
        if len(img.shape) == 3:
            return img[:, ::-1, :]
        else:
            return img[:, ::-1]
    else:
        return img