Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
regex, 7 lines solution in Clear category for Write Quadratic Equation by kdim
from re import sub
def quadr_equation(data) -> str:
(a, x1), x2 = (data[:2]), data[-1]
quad = f'{a}*x**2+{-a * x1 - a * x2}*x+{a * x1 * x2} = 0' # get str like - "-1*x**2+-1*x+0 = 0"
quad = sub(r'(\+|\-)0\*x(\*\*2)?|\+0', r'', quad) # remove zeros - "0*x"->"" , "+0"->""
quad = sub(r'(\+|\-)?1\*|\+(\-)', r'\1\2', quad) # remove ones - "1*x"->"x" , "+-"->"-"
return sub(r'(.)(\+|\-)', r'\1 \2 ', quad) # add spaces - "-"->" - ", "+"->" + "
Sept. 16, 2022
Comments: