diff --git a/numpy_questions.py b/numpy_questions.py index 07a10c1..5214d20 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -1,4 +1,5 @@ -"""Assignment - using numpy and making a PR. +""" +Assignment - using numpy and making a PR. The goals of this assignment are: * Use numpy in practice with two easy exercises. @@ -19,49 +20,51 @@ def max_index(X): - """Return the index of the maximum in a numpy array. - - Parameters - ---------- - X : ndarray of shape (n_samples, n_features) - The input array. - - Returns - ------- - (i, j) : tuple(int) - The row and columnd index of the maximum. - - Raises - ------ - ValueError - If the input is not a numpy array or - if the shape is not 2D. """ - i = 0 - j = 0 + Return the indices (i, j) of the maximum value in a 2D matrix. + + Parameters: + X (np.ndarray): A 2D numpy array. - # TODO + Returns: + tuple: Indices (i, j) of the maximum value in the array. + + Raises: + ValueError: If X is not a numpy array or not a 2D array. + """ + if not isinstance(X, np.ndarray): + raise ValueError("X must be a numpy array.") + if X.ndim != 2: + raise ValueError("X must be a 2D array.") + # Find the flattened index of the maximum value + flat_index = np.argmax(X) + # Convert to 2D indices + i, j = divmod(flat_index, X.shape[1]) return i, j def wallis_product(n_terms): - """Implement the Wallis product to compute an approximation of pi. + """ + Approximate the value of pi using the Wallis product. - See: - https://en.wikipedia.org/wiki/Wallis_product + Parameters: + n_terms (int): The number of terms in the Wallis product. - Parameters - ---------- - n_terms : int - Number of steps in the Wallis product. Note that `n_terms=0` will - consider the product to be `1`. + Returns: + float: Approximation of pi. - Returns - ------- - pi : float - The approximation of order `n_terms` of pi using the Wallis product. + Raises: + ValueError: If n_terms is negative. """ - # XXX : The n_terms is an int that corresponds to the number of - # terms in the product. For example 10000. - return 0. + if not isinstance(n_terms, int) or n_terms < 0: + raise ValueError("n_terms must be a non-negative integer.") + + product = 1.0 + if n_terms == 0: + return 2.0 + + for i in range(1, n_terms + 1): + product *= (4 * i**2) / (4 * i**2 - 1) + + return 2 * product