How to find the maximum by comparing previous value?
<p>I have a huge data set &amp; complex code that it takes so much time if I am trying to find the maximum by appending all intermediate results and compare. So I want to implement algorithm to find the maximum by comparing previous value.
my algorithm goes like, </p>

<pre><code>for i in range(len(y)):
  oldmax = y[0]
  if oldmax &gt;= y[i]:
    pass
  else:
    new_max = y[i]
</code></pre>

<p>then I want to store this newmax and compare with next string y[i+1] and go on (Only the maximum value should survive at the end).
But I am not sure how to set this new_max to be something to be compared in the next loop. For example, let y = [3,1,5,6,4]. Since the y[0] is greater than y[1], it will pass until it meets 5. But since 6 and 4 are also greater than 3, the new_max ends up being 4 which is the last value.</p>

<p>How should I fix the code? Any help will be appreciated!</p>

<p>Why don't you just use one variable and compare until <code>length - 1</code>? Also, you keep resetting <code>oldmax</code> to the first element on every iteration, causing inaccurate results. Set it's initial value but don't change it:</p>

<pre><code>max_value = y[0]
for i in range(len(y) - 1):
    if max_value &lt;= y[i + 1]
        max_value = y[i + 1]
</code></pre>

<p>Now what does is just has one variable, <code>max_value</code> which has an initial value of the first element. The loop goes from first element to <code>length - 1</code>, due to the accessing of element <code>i + 1</code>. If the max is less than the next value, reassign max to the next value. I also eliminated the extra if that did nothing and only checked if it was larger. </p>

<hr>

<p>You can get rid of all the code above by just using the builtin <a href="https://docs.python.org/2/library/functions.html#max" rel="nofollow"><code>max</code></a> function which takes in any iterable and returns the maximum value:</p>

<pre><code>max_value = max(y)
</code></pre>

python arrays database max