Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import click
- from math import sqrt
- from functools import wraps
- from random import randint
- def retry_on_exception(attempts = 1):
- def decorator(func):
- @wraps(func)
- def wrapper(*args, **kwargs):
- for i in range(attempts):
- try:
- result = func(*args, **kwargs)
- except Exception as e:
- if i == attempts - 1:
- raise e
- else:
- continue
- else:
- return result
- return wrapper
- return decorator
- @retry_on_exception(3)
- def test_random_even():
- num = randint(1, 10)
- assert num % 2 == 0
- class EquationSolver:
- @staticmethod
- def solve_square(a, b, c):
- D = b ** 2 - 4 * a * c
- if D < 0:
- return
- elif D == 0:
- yield -b / (2 * a)
- else:
- yield (-b + sqrt(D)) / (2 * a)
- yield (-b - sqrt(D)) / (2 * a)
- @staticmethod
- def solve_linear(a, b, c, d):
- if a - c == 0:
- return
- yield (d - b) / (a - c)
- def test_linear_D_zero():
- assert list(EquationSolver.solve_linear(1, 2, 2, 0)) == [2]
- def test_linear_normal():
- assert list(EquationSolver.solve_linear(1, 2, 3, 4)) == [-1]
- def test_linear_zero():
- assert list(EquationSolver.solve_linear(1, 2, 1, 4)) == []
- def test_linear_infinite():
- assert list(EquationSolver.solve_linear(1, 2, 1, 2)) == []
- def test_square_normal():
- assert list(EquationSolver.solve_square(1, 2, 1)) == [-1]
- assert list(EquationSolver.solve_square(1, 2, -3)) == [1, -3]
- def test_square_complex():
- assert list(EquationSolver.solve_square(1, 2, 3)) == []
- def test_square_no_B_C():
- assert list(EquationSolver.solve_square(1, 0, 0)) == [0]
- def testAll():
- print("Testing linear")
- test_linear_D_zero()
- test_linear_normal()
- test_linear_zero()
- test_linear_infinite()
- print("Testing square")
- test_square_normal()
- test_square_complex()
- test_square_no_B_C()
- print("Test retry on exception")
- test_random_even()
- print("All tests passed")
- """
- 1. linear: читает параметры a, b, c, d из консоли и выводит результат работы solve_linear
- 2. square: читает параметры a, b, c из консоли и выводит результат работы solve_square
- 3. tests: запускает тесты
- """
- @click.group()
- def cli():
- pass
- @cli.command()
- def linear():
- a, b, c, d = map(float, input().split())
- solves = EquationSolver.solve_linear(a, b, c, d)
- try:
- first = next(solves)
- print("x = {}".format(first))
- except StopIteration:
- print("No solutions")
- else:
- for x in solves:
- print("x = {}".format(x))
- @cli.command()
- def square():
- a, b, c = map(float, input().split())
- solves = EquationSolver.solve_square(a, b, c)
- try:
- first = next(solves)
- print("x = {}".format(first))
- except StopIteration:
- print("No solutions")
- else:
- for x in solves:
- print("x = {}".format(x))
- @cli.command()
- def tests():
- print("Running tests...")
- testAll()
- print("Tests passed")
- if __name__ == '__main__':
- test_random_even()
- cli()
Advertisement
Add Comment
Please, Sign In to add comment