How to calculate the maximum sum in a reverse way in pandas list

Question:

I have this list:

balance = [300,400,250,100,50,1,2,0,10,15,25,20,10,1,0,10,15]

I need to calculate the maximum consecutive increase in balance over a certain period of time.
The first element on the right is the most recent.

For example, I need to calculate the maximum consecutive increases in balance over the most recent 10 occurrences.
From the list above, I’d take the most recent 10 occurrences:

[0,10,15,25,20,10,1,0,10,15]

Count the consecutive increases (by adding 1 every time there is an increase, else reset the counter):

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

And then take the maximum (which is 3).

Does anyone know how to code it in Python?

Asked By: Giampaolo Levorato

||

Answers:

You can use the Pandas library in Python to calculate the maximum consecutive increase in a list

balance = [300,400,250,100,50,1,2,0,10,15,25,20,10,1,0,10,15]
recent_balance = balance[-10:]
max_consecutive_increases = 0
current_count = 0

for i in range(1, len(recent_balance)):
    if recent_balance[i] > recent_balance[i-1]:
        current_count += 1
        max_consecutive_increases = max(max_consecutive_increases, current_count)
    else:
        current_count = 0

print(max_consecutive_increases)
Answered By: renjith

You can do in plain(vanilla) python like this:

c=0
r = [0,10,15,25,20,10,1,0,10,15]
k=[]
for x in range(len(r)-1):
  if r[x]<r[x+1]:
    c+=1
    k.append(c)
  else:
    c=0
    k.append(c)

print(k)
[1, 2, 3, 0, 0, 0, 0, 1, 2]

print(max(k))
3
Answered By: God Is One
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.