The following exercises provide you with the opportunity to practice with speeding up your code. The solutions to these exercises are found in the section, Chapter 4 .
-
Replace the question marks in the following table to describe how many steps occur for a given number of data elements across various types of Big O:
N Elements O(N) O(log N) O(N 2 ) 100 100 ? ? 2000 ? ? ? -
If we have an O(N 2 ) algorithm that processes an array and find that it takes 256 steps, what is the size of the array?
-
Use Big O Notation to describe the time complexity of the following function. It finds the greatest product of any pair of two numbers within a given array:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>greatestProduct</strong> (array):</td></tr><tr><td> <span> </span></td><td>greatestProductSoFar = array[0] array[1]</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>for</strong> i, iVal <strong>in</strong> enumerate(array):</td></tr><tr><td> <span> </span></td><td> <strong>for</strong> j, jVal <strong>in</strong> enumerate(array):</td></tr><tr><td> <span> </span></td><td> <strong>if</strong> i != j <strong>and</strong> iVal jVal > greatestProductSoFar:</td></tr><tr><td> <span> </span></td><td>greatestProductSoFar = iVal * jVal</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>return</strong> greatestProductSoFar</td></tr></tbody></table>
-
The following function finds the greatest single number within an array, but has an efficiency of O(N 2 ). Rewrite the function so that it becomes a speedy O(N):
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>greatestNumber</strong> (array):</td></tr><tr><td> <span> </span></td><td> <strong>for</strong> i <strong>in</strong> array:</td></tr><tr><td> <span> </span></td><td> <em># Assume for now that i is the greatest:</em> </td></tr><tr><td> <span> </span></td><td>isIValTheGreatest = True</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>for</strong> j <strong>in</strong> array:</td></tr><tr><td> <span> </span></td><td> <em># If we find another value that is greater than i,</em> </td></tr><tr><td> <span> </span></td><td> <em># i is not the greatest:</em> </td></tr><tr><td> <span> </span></td><td> <strong>if</strong> j > i:</td></tr><tr><td> <span> </span></td><td>isIValTheGreatest = False</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <em># If, by the time we checked all the other numbers, i</em> </td></tr><tr><td> <span> </span></td><td> <em># is still the greatest, it means that i is the greatest number:</em> </td></tr><tr><td> <span> </span></td><td> <strong>if</strong> isIValTheGreatest:</td></tr><tr><td> <span> </span></td><td> <strong>return</strong> i</td></tr></tbody></table>
Copyright © 2020, The Pragmatic Bookshelf.