ahmet / Python-for-Data-Science
Herkese Açık Ahmet Kerem Piscine Final
ft_calculator.py 1.7 KB
class calculator:
"""Compute a vector of numbers against a scalar.
Every operation updates the vector held by the calculator and
prints the result, so the operations can be chained.
"""
def __init__(self, vector: list) -> None:
"""Build a calculator holding the vector to work on."""
self.vector = vector
def __add__(self, object) -> None:
"""Add the scalar to each value of the vector and print it."""
self.vector = [value + object for value in self.vector]
print(self.vector)
def __mul__(self, object) -> None:
"""Multiply each value of the vector by the scalar and print it."""
self.vector = [value * object for value in self.vector]
print(self.vector)
def __sub__(self, object) -> None:
"""Remove the scalar from each value of the vector and print it."""
self.vector = [value - object for value in self.vector]
print(self.vector)
def __truediv__(self, object) -> None:
"""Divide each value of the vector by the scalar and print it.
A division by zero is reported and leaves the vector untouched.
"""
if object == 0:
print("Error: division by zero is not allowed")
return
self.vector = [value / object for value in self.vector]
print(self.vector)
def main() -> None:
"""Test the calculator against a scalar."""
v1 = calculator([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
v1 + 5
print("---")
v2 = calculator([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
v2 * 5
print("---")
v3 = calculator([10.0, 15.0, 20.0])
v3 - 5
v3 / 5
print("---")
v3 / 0
if __name__ == "__main__":
main()