forked from uchicago-cs/python-practice-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clip_values.py
88 lines (63 loc) · 2.73 KB
/
clip_values.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def clip_values(x, min_val=None, max_val=None):
"""
Return a new array with the values clipped.
If min_val is set, all values < min_val will be set to min_val
If max_val is set, all values > max_val will be set to max_val
Remember to return a new array, NOT to modify the input array.
Inputs:
x: the n-dimensional array to be clipped
min_val : the minimum value in the returned array (if not None)
max_val : the maximum value in the returned array (if not None)
returns: an array with the same dimensions of X with values clipped
to (min_val, max-val)
"""
# YOUR CODE HERE
# Replace None with an appropriate return value
return None
#############################################################
### ###
### Testing code. ###
### !!! DO NOT MODIFY ANY CODE BELOW THIS POINT !!! ###
### ###
#############################################################
import sys
import numpy as np
sys.path.append('../')
import test_utils as utils
def test_clip_values():
x = np.linspace(0, 2, 10)
x_orig = x.copy()
### Check for modification of input array
recreate_msg = utils.gen_recreate_msg('clip_values', 1, 1.8)
result = clip_values(x, min_val=1, max_val=1.8)
utils.check_none(result, recreate_msg)
utils.check_is_ndarray(result, recreate_msg)
assert np.allclose(x, x_orig), \
"\n Input array was modified.\n\n" + recreate_msg
### Check minimum value
recreate_msg = utils.gen_recreate_msg('clip_values', 1)
result = clip_values(x, min_val=1)
utils.check_none(result, recreate_msg)
utils.check_is_ndarray(result, recreate_msg)
assert np.min(result) == 1.0,\
"\n The minimum value of the array is not 1.0\n\n" \
+ recreate_msg
### Check maximum value
recreate_msg = utils.gen_recreate_msg('clip_values', None, 1)
result = clip_values(x, max_val=1)
utils.check_none(result, recreate_msg)
utils.check_is_ndarray(result, recreate_msg)
assert np.max(result) == 1.0, \
"\n The maximum value of the array is not 1.0\n\n" \
+ recreate_msg
### Check Both
recreate_msg = utils.gen_recreate_msg('clip_values', 1.0, 1.5)
result = clip_values(x, min_val=1.0, max_val=1.5)
utils.check_none(result, recreate_msg)
utils.check_is_ndarray(result, recreate_msg)
assert np.max(result) == 1.5, \
"\n The maximum value of the array is not 1.5\n\n"\
+ recreate_msg
assert np.min(result) == 1.0, \
"\n The minimum value of the array is not 1.0\n\n"\
+ recreate_msg