Search code examples
pythonmathreturn

Pretty print a factorized polynomial


from math import sqrt

def factor(a, b, c):
  x1 = (-1 * b) + sqrt(b * b - (4 * a * c))
  x2 = (-1 * b) - sqrt(b * b - (4 * a * c))
  solution1 = (x1 / (2 * a))
  solution2 = (x2 / (2 * a))
  expression1 = ['x', (-1 * solution1)]
  expression2 = ['x', (-1 * solution2)]
  return expression1, expression2

print(factor(1, -17, 12))

I cannot figure out how to replace the values in the list to make the output look cleaner. I have tried arranging the values in different orders and adding strs to make it look better, but to no avail.

How can I make the output look like (x - 16.2)(x - 0.73) instead of (['x', -16.262087348130013], ['x', -0.7379126518699879])? I have not been successful in removing the unnecessary characters from the output.

I just want to remove the bracets and quotes.


Solution

  • Here's a painfully spread out (and ugly) solution, but one which should be useful as you learn the formatting and other tricks required to get this exactly as you want:

    def pretty_product(e1, e2):
        a = e1[0]
        op1 = '+' if e1[1] >= 0 else '-'
        b = e1[1]
        c = e2[0]
        op2 = '+' if e2[1] >= 0 else '-'
        d = e2[1]
        return f'({a} {op1} {abs(b):.2f})({c} {op2} {abs(d):.2f})'
    
    print(pretty_product(['x', 2567.235235], ['y', -423.12313124214]))
    

    Result is:

    (x + 2567.24)(y - 423.12)
    

    Note: if you want to suppress a possible + 0.00 you have more code to write, but it should be easy to add, I think. :)