Quantcast
Viewing all articles
Browse latest Browse all 15

Answer by Prodipta Ghosh for Count and summation of positive and negative number sequences

In Python, apart from defining a class to store the memory variables, you can use a closure to achieve the same.

def run():    count = 0    last_sign = 0    def sign(i):        return 1 if i > 0 else -1    def f(i):        nonlocal count        nonlocal last_sign        if sign(i) == last_sign:            count = count+1        else:            last_sign = sign(i)            count = 1        return count    return ff = run()y = [f(i) for i in x]

Note this works for Python 3 only (in Python 2 I think you cannot modify the closure variable like this). Similar thing for summation as well.


Viewing all articles
Browse latest Browse all 15

Trending Articles