D
D
Danil Samodurov2021-08-15 21:53:46
Python
Danil Samodurov, 2021-08-15 21:53:46

Why is there an error in the code?

Hello. In search of speeding up the calculation of the exponential moving average, I decided to write a recursive algorithm for this. I love recursion and try to use it more often.
Here is the actual code:

def get_ema(array, N: int, prev_ema: float = None):
    alpha = 2 / (1 + N)
    if len(array) == 1:
        ema = []
        ema.append(array[0] * alpha + (1 - alpha) * prev_ema)
        return ema

    if not prev_ema:
        for_sma = array[:N]
        sma = sum(for_sma) / len(for_sma)
        return get_ema(array[N:], N, prev_ema=sma).append(sma)
    else:
        new_ema = array[0] * alpha + (1 - alpha) * prev_ema
        return get_ema(array[1:], N, prev_ema=new_ema).append(new_ema)

On startup, an AttributeError: 'NoneType' object has no attribute 'append' error points to the last line. I don't understand why. It seems that the list should return, so append should work. Where did I go wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-08-15
@samodurOFF

append()returns None. So any return(except return ema) will return None. Well, at the next iteration, the code will crumble.
You can quickly check by replacing the first if block

tmp = get_ema(array[N:], N, prev_ema=sma)
print(type(tmp))
return tmp.append(sma)

and second
tmp = get_ema(array[1:], N, prev_ema=new_ema)
print(type(tmp))
return tmp.append(new_ema)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question