pythonpandasrecursionalgebra

Python arithmetic function with recursion


This might be done with a rolling function in pandas probably, not sure but I would like to apply the following function for a list, the current state S in position x is defined as

S[x] = if S[x-1] > 0 S[x-1] -1 + S[x] else S[x] -1 for x > 1 

It can be understood as the current state -1 and the current state... This is because I need to do a kind of cumulative sum of all the previous positions -1 + the current position.

An example for the list

[1,1,2,0,0,2]

returns this values

[0,0,1,0,-1,1]

because:

S[0] = 1 - 1 = 0
S[1] = S[1] - 1 + S[0] = 1 - 1 + 0 = 0
S[2] = S[2] - 1 + S[1] = 2 - 1 + 0 = 1
S[3] = S[3] - 1 + S[2] = 0 - 1 + 1 = 0
S[4] = S[4] - 1 + S[3] = 0 - 1 + 0 = -1
S[5] = S[5] - 1 (no S[4] because the else rule being smaller than 0) = 2 - 1 = 1 

I am pretty sure this can probably be done in pandas but I am also open to a standard python function I send a list to (prefer pandas though).

Have been trying recursion and failed miserably.


Solution

  • subtract 1 then use cumsum

    (s-1).cumsum()
    
    0    0
    1    0
    2    1
    3    0
    4   -1
    5    0
    

    here you go, revised solution to accommodate of condition in calculating cumulative sum

    np.where(((s.shift(1) - 1).cumsum()) > 0, 
             (s-1).cumsum(), 
              s-1)
    
    [ 0,  0,  1,  0, -1,  1]