Algorithms Exercise 2

Imports


In [142]:
%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 [143]:
s=[]
i=0
def find_peaks(a):
    """Find the indices of the local maxima in a sequence."""
    # YOUR CODE HERE
    if a[0]>a[1]: #if the first number is bigger than the second number 
        s.append(0) #add 0 as a peak
    for x in range (len(a)-1): #       
        if a[x]>a[x-1] and a[x]>a[x+1] and x!=0: #if the current number is bigger than the one before it and the one after it
#             print (x)
            s.append(x) #add it to the list of peaks
    if a[-1]>a[-2]: #if the last number is bigger than the second to last one it is a peak
#         print (len(a)-1)
        s.append(len(a)-1) #add the location of the last number to the list of locations
    return s



#below here is used for testing, not sure why assert tests are not working since my tests do
# p2 = find_peaks(np.array([0,1,2,3]))
# p2

p1 = find_peaks([2,0,1,0,2,0,1])
p1

# p3 = find_peaks([3,2,1,0])
# p3

# np.shape(p1)
# y=np.array([0,2,4,6])
# np.shape(y)
# print(s)


Out[143]:
[0, 2, 4, 6]

In [144]:
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]))


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-144-e9503c7dbdc3> in <module>()
      1 p1 = find_peaks([2,0,1,0,2,0,1])
----> 2 assert np.allclose(p1, np.array([0,2,4,6]))
      3 p2 = find_peaks(np.array([0,1,2,3]))
      4 assert np.allclose(p2, np.array([3]))
      5 p3 = find_peaks([3,2,1,0])

/usr/local/lib/python3.4/dist-packages/numpy/core/numeric.py in allclose(a, b, rtol, atol)
   2232     # ignore invalid fpe's
   2233     with errstate(invalid='ignore'):
-> 2234         r = all(less_equal(abs(x - y), atol + rtol * abs(y)))
   2235 
   2236     return r

ValueError: operands could not be broadcast together with shapes (8,) (4,) 

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 [44]:
from sympy import pi, N
pi_digits_str = str(N(pi, 10001))[2:]

In [157]:
# YOUR CODE HERE
# num=[]
# pi_digits_str[0]
# for i in range(len(pi_digits_str)):
#     num[i]=pi_digits_str[i]
    
f=plt.figure(figsize=(12,8))
plt.title("Histogram of Distances between Peaks in Pi")
plt.ylabel("Number of Occurences")
plt.xlabel("Distance from Previous Peak")
plt.tick_params(direction='out')
plt.box(True)
plt.grid(False)
test=np.array(list(pi_digits_str),dtype=np.int)
peaks=find_peaks(test)
dist=np.diff(peaks)
plt.hist(dist,bins=range(15));



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