Skip to content

Commit 6d6542a

Browse files
committed
UP my solution
1 parent d31f7ef commit 6d6542a

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

numpy_questions.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
"""Assignment - using numpy and making a PR.
2-
32
The goals of this assignment are:
43
* Use numpy in practice with two easy exercises.
54
* Use automated tools to validate the code (`pytest` and `flake8`)
@@ -20,17 +19,14 @@
2019

2120
def max_index(X):
2221
"""Return the index of the maximum in a numpy array.
23-
2422
Parameters
2523
----------
2624
X : ndarray of shape (n_samples, n_features)
2725
The input array.
28-
2926
Returns
3027
-------
3128
(i, j) : tuple(int)
3229
The row and columnd index of the maximum.
33-
3430
Raises
3531
------
3632
ValueError
@@ -39,29 +35,34 @@ def max_index(X):
3935
"""
4036
i = 0
4137
j = 0
42-
4338
# TODO
44-
39+
# error handling
40+
if not isinstance(X, np.ndarray):
41+
raise ValueError("The input is not a numpy array")
42+
if len(X.shape) != 2:
43+
raise ValueError("The shape is not 2D")
44+
i, j = np.unravel_index(np.argmax(X), X.shape)
4545
return i, j
4646

4747

4848
def wallis_product(n_terms):
4949
"""Implement the Wallis product to compute an approximation of pi.
50-
5150
See:
5251
https://en.wikipedia.org/wiki/Wallis_product
53-
5452
Parameters
5553
----------
5654
n_terms : int
5755
Number of steps in the Wallis product. Note that `n_terms=0` will
5856
consider the product to be `1`.
59-
6057
Returns
6158
-------
6259
pi : float
6360
The approximation of order `n_terms` of pi using the Wallis product.
6461
"""
6562
# XXX : The n_terms is an int that corresponds to the number of
6663
# terms in the product. For example 10000.
67-
return 0.
64+
65+
product = 2.0
66+
for i in range(1, n_terms + 1):
67+
product *= (4 * i ** 2) / (4 * i ** 2 - 1)
68+
return product

0 commit comments

Comments
 (0)