i am suppose to solve this question but i am stuck.
Write a program to find the time period(s) of the largest price drop(s) when a list of price(s) is given. For instance, if the list is [300,301,303,299,300,298,301,305], then there is one period of the largest price drop: from time 2 with price 303 to time 5 with price 298.
Below is my solution but there is a flaw
def maxdrop(p):
high = low = drop = newhigh = 0
for i in range(len(p)):
if p[i] >= p[high]:
newhigh = i # invariant: p[high] <= p[newhigh]
else: # so: p[i] < p[high] <= p[newhigh]
newdrop = p[newhigh] - p[i]
if newdrop >= drop:
high, low, drop = newhigh, i, newdrop
return ((high, p[high]), (low, p[low]), drop)
def test():
p = [20,22,19,20,24,18,21,24,27]
print p, maxdrop(p)
p = list(reversed(p))
print p, maxdrop(p)
if __name__ == "__main__":
test()
If you try with the below list
[2,1,2,3,4,3,2]
the sharpest drop should occurs over 4,3,2 – the last 3 elements.
But with my code, the output is 2,1 – the first 2 elements.
Please assist, thanks!
Here’s my try at it. It works correctly on all the examples that you gave.
I basically just go through the array and when there is a drop between two points, referring to the first point as A, look ahead until there is a value that is higher than A. I keep track of the minimum in this region. If the difference between A and the minimum is a bigger drop than what I’ve already found, I hold onto it. I then start looking again for a drop between two points, starting at the next point that was higher than A.
Here’s the code. It isn’t very Python-esque, but it works pretty well (I’d just go to Cython if I needed it to be faster). Also, it returns the magnitude of the drop.
A big problem with your code is that you only look at the next value for the biggest drop after a new high value is found.