1
- """Assignment - using numpy and making a PR.
2
-
3
- The goals of this assignment are:
4
- * Use numpy in practice with two easy exercises.
5
- * Use automated tools to validate the code (`pytest` and `flake8`)
6
- * Submit a Pull-Request on github to practice `git`.
7
-
8
- The two functions below are skeleton functions. The docstrings explain what
9
- are the inputs, the outputs and the expected error. Fill the function to
10
- complete the assignment. The code should be able to pass the test that we
11
- wrote. To run the tests, use `pytest test_numpy_question.py` at the root of
12
- the repo. It should say that 2 tests ran with success.
13
-
14
- We also ask to respect the pep8 convention: https://pep8.org.
15
- This will be enforced with `flake8`. You can check that there is no flake8
16
- errors by calling `flake8` at the root of the repo.
17
- """
18
1
import numpy as np
19
2
20
3
@@ -29,19 +12,22 @@ def max_index(X):
29
12
Returns
30
13
-------
31
14
(i, j) : tuple(int)
32
- The row and columnd index of the maximum.
15
+ The row and column index of the maximum.
33
16
34
17
Raises
35
18
------
36
19
ValueError
37
20
If the input is not a numpy array or
38
21
if the shape is not 2D.
39
22
"""
40
- i = 0
41
- j = 0
23
+ if not isinstance ( X , np . ndarray ):
24
+ raise ValueError ( "Input must be a numpy array." )
42
25
43
- # TODO
26
+ if X .ndim != 2 :
27
+ raise ValueError ("Input array must be 2D." )
44
28
29
+ max_idx = np .argmax (X )
30
+ i , j = np .unravel_index (max_idx , X .shape )
45
31
return i , j
46
32
47
33
@@ -62,6 +48,10 @@ def wallis_product(n_terms):
62
48
pi : float
63
49
The approximation of order `n_terms` of pi using the Wallis product.
64
50
"""
65
- # XXX : The n_terms is an int that corresponds to the number of
66
- # terms in the product. For example 10000.
67
- return 0.
51
+ if n_terms == 0 :
52
+ return 2.0
53
+
54
+ k = np .arange (1 , n_terms + 1 )
55
+ product = np .prod ((4.0 * k * k ) / (4.0 * k * k - 1.0 ))
56
+ pi_approx = 2.0 * product
57
+ return pi_approx
0 commit comments