iLuvMeat - 2 months ago 202

Python Question

Here's my code, this should return 45 as answer instead I'm getting 8.

This code works fine for smaller lists.

I get proper answer for this list [1, 2, 3, 2, 1] as 6.

`def longest_run(L):`

bestDec = 0

bestInc = 0

currentSum = 0

lastNum = 0

for i in L:

if i <= lastNum:

currentSum += i

else:

if currentSum > bestDec:

bestDec = currentSum

currentSum = i

lastNum = i

currentSum = 0

lastNum = 0

for i in L:

if i >= lastNum:

currentSum += i

else:

if currentSum > bestInc:

bestInc = currentSum

currentSum = i

lastNum = i

if bestDec >= bestInc:

return bestDec

else:

return bestInc

L = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print(longest_run(L))

Answer

If you want to find the cumulative sum of a list of integers till they are increasing, what about:

```
def longest_run(L):
if len(L)==0: return 0
cs = L[0]
for i in range(1,len(L)):
if L[i]>L[i-1]:
cs+=L[i]
else:
break
return cs
```