Python: First test function

Question:

I am attempting to make a test for a piecewise function that computes both sin(x) > 0 and sin(x) < 0

from math import sin

def f(x):
    if x > 0:
        return sin(x)
    elif x <= 0:
        return 0
    
print(f(2)) # = 0.9092974268256817
print(f(-2)) # = 0

def test_f():
    inputs = [[-2], [2]]
    answers = [0, 0.9092974268256817]
    for i in range(len(inputs)):
        computed = f(inputs[i])
        expected = answers[i]
        tolerance = 1e-10
        success = abs(computed == expected) < tolerance
        message = "Values are not matching"
        assert success, message

test_f()

I am getting error

if x > 0:
TypeError: '>' not supported between instances of 'list' and 'int'

My lack of Python skills is making me stuck. Also is my for-loop correct in the test function?

Asked By: Laxen1900

||

Answers:

Your code is OK, but you’re using lists wrong to store your data. When you store data in a list, you. only need one set of brackets. Your inputs variable [[-2], [2]], but it should be [-2, 2] instead.

Answered By: Michael M.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.