Почему эта кусочная функция не проходит проверку утверждения типа объекта? - PullRequest
0 голосов
/ 05 мая 2020

Мне нужно создать кусочную функцию в Python, что я и сделал, и мне нужно выполнить пару тестов. В итоге я создал код, который создает график, и второй код для условий, которым я должен соответствовать ... Я не знал, как включить условия в векторизованную версию кода, и я не мог понять, как построить мой более длинный код со всеми условиями в нем.

Если бы вы могли помочь с этим, это было бы здорово, но меня больше всего беспокоит проверка утверждения. Вот два кода: Код с условиями не соответствует типу утверждения (out [4]) в части [float, np.float64], но я не знаю почему, поскольку, похоже, он выполняет тип утверждения (out [1 ]) в [float, np.float64] в порядке. Спасибо

import matplotlib.pyplot as plt
import numpy as np
from nose.tools import assert_equal, assert_raises
import warnings
# this is the code for the plot (vectorised form?)
def pwfun(x):
    x = np.asarray(x)
    y = np.zeros(x.shape)
    y += ((x >= -1) & (x <= 1)) * 0
    y += (x > 1) * (x*x - 1)
    y += (x < -1) * (-2*x - 2)
    return y
    raise NotImplementedError

# print(pwfun(x = [-6.0, -0.5 , 0.2,  7]))
# print(pwfun([-2, 0.5, 3]))
x = np.linspace(-4,3)
plt.plot(x,pwfun(x), 'r')
plt.show()
# I couldn't figure out a way to make the bottom one show a plot.

   # this is the code for meeting the conditions

def pwfun(x):
    blah=[]
    if isinstance(x, list):
        for i in x:
            if i < -1:
                if isinstance(i, float):
                    blah.append(round(-2 * i - 2))
                else:
                    blah.append( int(-2 * i - 2))
            elif ((i <= 1) and (i >= -1)):
                blah.append( 0)
            else:
                if isinstance(i, float):
                    blah.append(round(i * i - 1 , 2))
                else:
                    blah.append(int(i * i - 1))
        return blah
    else:
        if (x < -1):
            if isinstance(x, float):
                return round(-2 * x - 2, 2)
            else:
                return int(-2 * x - 2)
        elif ((x <= 1) and (x >= -1)):
            return 0
        else:
            if isinstance(x, float):
                return round(x * x -1, 2)
            else:
                return int(x * x -1)
assert pwfun(-3) == 4
assert pwfun(0.56) == 0
assert pwfun(4) == 15

x = [-6.0, -0.5 , 0.2,  7]
assert pwfun(x) == [10, 0, 0, 48]
x = [-7/2, -2.5, -1, 0 , 1, 2, 3.2]
assert pwfun(x) == [5, 3, 0, 0, 0, 3, 9.24]
## testing whether the entries are of appropriate type


x = [-3.0, 2.3, -7/2, -2.5, -1.4]
out = pwfun(x)      

assert type(out[0]) == int  # int
assert type(out[1]) in [float, np.float64]  ## float | np.float64
assert type(out[2]) == int
assert type(out[3]) == int
assert type(out[4]) in [float, np.float64] # THIS IS THE PART THAT FAILS


...