diff --git a/numpy_questions.py b/numpy_questions.py index 07a10c1..1734736 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -15,11 +15,14 @@ This will be enforced with `flake8`. You can check that there is no flake8 errors by calling `flake8` at the root of the repo. """ + + import numpy as np def max_index(X): - """Return the index of the maximum in a numpy array. + """ + Return the index of the maximum in a numpy array. Parameters ---------- @@ -37,16 +40,25 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ + if not isinstance(X, np.ndarray): + raise ValueError("The input is not a numpy array") + if X.ndim != 2: + raise ValueError("The shape is not 2D") + """ + Return the index of the maximum in a numpy array + (The row and columnd index of the maximum) + """ i = 0 j = 0 - - # TODO - - return i, j + max_index = np.argmax(X) + i, j = np.unravel_index(max_index, X.shape) + # I convert to int just to avoid show the type(int64) in the output + return (int(i), int(j)) def wallis_product(n_terms): - """Implement the Wallis product to compute an approximation of pi. + """ + Implement the Wallis product to compute an approximation of pi. See: https://en.wikipedia.org/wiki/Wallis_product @@ -62,6 +74,12 @@ def wallis_product(n_terms): pi : float The approximation of order `n_terms` of pi using the Wallis product. """ - # XXX : The n_terms is an int that corresponds to the number of - # terms in the product. For example 10000. - return 0. + # So if n_terms = 0 -> product = 1 + product = 1.0 + for n in range(1, n_terms + 1): + """In wiki the wallis product = the infinite product + # representation of π 4*n^2/(4*n^2-1)""" + term = (4 * np.square(n)) / (4 * np.square(n) - 1) + product *= term + pi = 2 * product + return pi