Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Complete the function closest_value(values, scalar) which returns the clo

ID: 3598328 • Letter: P

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 = [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

Explanation / Answer

change result = None with result = values[np.absolute(values-scalar).argmin()]

here is your modified code

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 = values[np.absolute(values-scalar).argmin()]
# YOUR CODE HERE
return result

# copy pastable code link: https://paste.ee/p/yFlRo