Advertisement
Guest User

Untitled

a guest
Jan 21st, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. import re, math
  2.  
  3. class SquareEquationException(Exception):
  4.     pass
  5.  
  6. def solve_square_equation(eq):
  7.     eq = eq.lower().lstrip().rstrip().replace(' ', '')
  8.     eqreg = re.findall('(?:[-+]{0,1}[0-9]{0,100}x[\^]2|[-+]{1}[0-9]{0,100}x|[-+]{0,1}[0-9]{1,100})', eq)
  9.     try:
  10.         for i in eqreg:
  11.             if '^' in i:
  12.                 if (i[0] == '+' or i[0] == '-') and i[1] == 'x':
  13.                     a = int('%s1' % i[0])
  14.                 elif i[0] == 'x':
  15.                     a = 1
  16.                 else:
  17.                     a = int(i.split('x')[0])
  18.             elif 'x' in i:
  19.                 b = int(i.split('x')[0])
  20.             else:
  21.                 c = int(i)
  22.         D = b * b - 4 * a * c
  23.         print('a = %d\nb = %d\nc = %d\nD = %d'% (a,b,c,D))
  24.         if D < 0:
  25.             raise SquareEquationException
  26.         if D > 0:
  27.             x1 = int((-b + math.sqrt(D)) / 2 * a)
  28.             x2 = int((-b - math.sqrt(D)) / 2 * a)
  29.             roots = [x1, x2]
  30.             roots.sort()
  31.             print('x1, x2 =',roots)
  32.         if D == 0:
  33.             x = int((-b + math.sqrt(D)) / 2 * a)
  34.             print('x = [',x,']')
  35.     except Exception as ERR:
  36.         print(ERR)
  37.         raise SquareEquationException
  38.  
  39. eq = input()
  40. print(eq,'= 0')
  41. solve_square_equation(eq)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement