Algorithms Exercise 2

Imports


In [179]:
%matplotlib inline
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

Peak finding

Write a function find_peaks that finds and returns the indices of the local maxima in a sequence. Your function should:

  • Properly handle local maxima at the endpoints of the input array.
  • Return a Numpy array of integer indices.
  • Handle any Python iterable as input.

In [180]:
def find_peaks(a):
    """Find the indices of the local maxima in a sequence."""
    b=[]
    count=0
    while count<(len(a)):                   # while count (our index indicator) is less than the length of the sequence+1
        if count==len(a):
                break
        if count==0 and a[count]>a[count+1]:               # if the first element is greater than the 2nd, add the index number 
            b.append(count)                                # to our list b
            count+=2                                        # count is now 2. which means we will analyze the 3rd element.
            
            
            
        elif count==0 and a[count]<a[count+1]:       # if the first value is less than the 2nd, move to evaluating the 2nd element.
            count+=1          
            
            
        elif count==(len(a)-1) and (a[count]>a[count-1]):    # if count = the very last element, and is greater than the previous, append to b.
            b.append(count)
            count+=1
            
        elif count==(len(a)-1) and (a[count]<a[count-1]):
            break
            
            
        elif a[count]>a[count+1] and a[count]>a[count-1]:   # if the element is greater than elements before and after, append.
            b.append(count)
            count+=1                                        #count moves two over.
            
        
        elif a[count]<a[count+1] or a[count]<a[count-1]:        # if element isnt greater than elements before and after,
            count+=1                                            #move over to next element
            
    
            
    return b

In [181]:
print(find_peaks([0,1,2,3]))


[3]

In [182]:
p1 = find_peaks([2,0,1,0,2,0,1])
assert np.allclose(p1, np.array([0,2,4,6]))
p2 = find_peaks(np.array([0,1,2,3]))
assert np.allclose(p2, np.array([3]))
p3 = find_peaks([3,2,1,0])
assert np.allclose(p3, np.array([0]))

Here is a string with the first 10000 digits of $\pi$ (after the decimal). Write code to perform the following:

  • Convert that string to a Numpy array of integers.
  • Find the indices of the local maxima in the digits of $\pi$.
  • Use np.diff to find the distances between consequtive local maxima.
  • Visualize that distribution using an appropriately customized histogram.

In [183]:
from sympy import pi, N
pi_digits_str = str(N(pi, 10001))[2:]

In [185]:
a=pi_digits_str
b=[]
for i in a:
    b.append(int(i))
c=np.array(b)
find_peaks(c)


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-185-fcb4cb6683bf> in <module>()
      4     b.append(int(i))
      5 c=np.array(b)
----> 6 find_peaks(c)

<ipython-input-180-d69cd7c9bc81> in find_peaks(a)
     24 
     25 
---> 26         elif a[count]>a[count+1] and a[count]>a[count-1]:   # if the element is greater than elements before and after, append.
     27             b.append(count)
     28             count+=1                                        #count moves two over.

KeyboardInterrupt: 

In [158]:



Out[158]:
[1, 2, 3, 4]

In [138]:
assert True # use this for grading the pi digits histogram

In [ ]: