Question: Python Complete the function closest_value(values, scalar) which returns the closest value to the input scalar among an numpy array of values. For example, if values
Python
Complete the function closest_value(values, scalar) which returns the closest value to the input scalar among an numpy array of values. For example, if values = [1, 5, 4, 18] and scalar = 17, then 18 would be returned as the net difference(regardless of whether the difference was positive or negative) between 18 and 17 is the least amongst all the numbers in the values array. Reminder: you can perform basic operations (i.e. +, -, /, %) on numpy arrays. For example: [1, 5, 4, 18] - 4 = [-3, 1, 0, 14] assuming the array was a numpy array. Hint: the function argmin() on a numpy array returns the index of the minimum value element in the array. Set result equal to the return value and return result.
a = np.asarray([1, 5, 4, 18]) print(a - 4) # should print [-3, 1, 0, 14] print(a.argmin()) # should print index 0 since 1 is minimum element
def closest_value(values, scalar):
%matplotlib inline
# plotting tools import numpy as np from scipy.spatial.distance import cdist import matplotlib.pyplot as plt from nose.tools import assert_equal, assert_true, assert_almost_equal from numpy.testing import assert_array_almost_equal
""" Returns the closest_value Parameters ---------- values: numpy array scalar: numpy.float64 Returns ------- numpy.float64 """ result = None # YOUR CODE HERE return result
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
