def npv(Rn, i, i0, pe=0):
    """Net present value (NPV) is the difference between
    the present value of cash inflows and the present value
    of cash outflows over a period of time.

    Args:
        Rn: Expected return list
        i: Discount rate
        i0: Initial amount invested
        pe: Profit or expense at the end of investment

    Returns:
        Net present value

    Example:
        Given the expected return list `Rn`, `i` as
        discount rate, and `i0` as initial amount invested
        you can calcuate NPV like this:

        >>> import malee
        >>> malee.npv([5000, 8000, 12000, 30000], 0.05, 40000)
        7065.266015703324
    """
    npv_sum = 0
    for idx, Ri in enumerate(Rn):
        if Ri == Rn[-1] and pe != 0:
            npv_sum += Ri + pe / ((1 + i) ** (idx + 1))
        else:
            npv_sum += Ri / ((1 + i) ** (idx + 1))
    return npv_sum - i0