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?
CodePudding user response:
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
CodePudding user response:
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)