In [179]:
%matplotlib inline
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
Write a function find_peaks that finds and returns the indices of the local maxima in a sequence. Your function should:
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]))
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:
np.diff to find the distances between consequtive local maxima.
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)
In [158]:
Out[158]:
In [138]:
assert True # use this for grading the pi digits histogram
In [ ]: