Browse Source

the method `Regression.predict()` requires 'x' or 'y' as keyword argument only

main
Holger Frey 2 years ago
parent
commit
fcb508f07f
  1. 15
      linear_regression.py

15
linear_regression.py

@ -19,13 +19,13 @@ class Regression:
def r2(self) -> float: def r2(self) -> float:
return self.score return self.score
def predict(self, x: int | float = None, y: int | float = None) -> float: def predict(self, *, x: int | float = None, y: int | float = None) -> float:
"""predict a value if x or y is given""" """predict a value if x or y is given"""
if x is not None: if x is not None:
return self.intercept + x * self.coefficient return self.intercept + x * self.coefficient
if y is not None: if y is not None:
return (y - self.intercept) / self.coefficient return (y - self.intercept) / self.coefficient
msg = "predict() expects 1 argument, got 0" msg = "predict() expects a keyword argument 'x' or 'y'"
raise TypeError(msg) raise TypeError(msg)
def to_dict(self): def to_dict(self):
@ -65,14 +65,21 @@ def test_linear_regression(example_data):
def test_regression_predict(example_data): def test_regression_predict(example_data):
regression = linear_regression(example_data, x="A", y="B") regression = linear_regression(example_data, x="A", y="B")
prediction = regression.predict(10) prediction = regression.predict(x=10)
assert pytest.approx(30.7) == prediction assert pytest.approx(30.7) == prediction
assert pytest.approx(10) == regression.predict(y=prediction) assert pytest.approx(10) == regression.predict(y=prediction)
with pytest.raises(TypeError, match="expects 1 argument"):
def test_regression_predict_exceptions(example_data):
regression = linear_regression(example_data, x="A", y="B")
with pytest.raises(TypeError, match="expects a keyword"):
regression.predict() regression.predict()
with pytest.raises(TypeError, match="takes 1 positional argument but"):
regression.predict(1)
def test_regression_to_dict(example_data): def test_regression_to_dict(example_data):
regression = linear_regression(example_data, x="A", y="B") regression = linear_regression(example_data, x="A", y="B")

Loading…
Cancel
Save