Python Chapter 7 Exercises plus (3)

Improve the function fun3, the parameter data is a list (may have multiple dimensions), num is a number, and returns the number with the largest difference between data and num. (Hint: np.abs, argmax, flat)

It should be noted here that the data may be multi-dimensional, so you can first convert the data to one-dimensional, and then find the largest difference.

def fun3(data=[1,2,3,4,5,6,7],num=5):
    """
    Arg:
        data : a list as input; e.g. [1,2,3,4,5,6,7]
    return a number; e.g. 1

    """
    data1=np.array(data)
    data2=np.array(list(data1.flat))
    diff=np.abs(data2-num)
    index=np.argmax(diff)
    return data2.flat[index]

Guess you like

Origin blog.csdn.net/qq_53029299/article/details/115279692