def gradient_RR_OLS(y, X, beta, lmbda):
    """
    Define the gradient for ordinary least squares and ridge regression
    :param y: observed values
    :param X: design matrix
    :param beta: parameter vector/ regression coefficients
    :param lmbda: When lam=0 it is OLS and otherwise ridge regression.
    :return: gradient of cost function
    """
    n = len(y)
    gradient = (-2 / n) * X.T @ (y - X @ beta) + 2 * lmbda * beta
    return gradient