I'm programming a math exam package that contains a module, root.py (and polynomial.py), which effectively represents a 1st order polynomial, or binomial. I would like to format the class Root:
object I've created to be visualized in its most reduced (human-readable) form. For example, if the root is of the form: ax + b
; where a
and b
represent coefficients of the root, the '+/-' should only exist if b
!= 0, and the a
term should omit the '+' sign if > 1, and omit the value 1
from the leading coefficient.
I've looked at this documentation, as well as this stack overflow article
Here's some relevant code:
root.py
class Root:
def __init__(self, a=0, b=0):
# Does stuff with a/b to get coefficients
def __str__(self):
a, b = '', '0'
### Begin code block of concern
if self.a:
b = ''
if self.a == 1:
a = 'x'
elif self.a == -1:
a = '-x'
else:
a = '{:-d}x'.format(self.a)
### End code block of concern
if self.b:
b = '{:+d}'.format(self.b)
return a + b # The string '{-}ax{+/-}b'
Examples:
- -3x+7, 3x-7 NOT +3x-7
- 7-3x, -7+3x NOT +7-3x
- -x-1, x+2 NOT -1x-1, +1x+2, or 1x+2
The above mentioned code already (sort-of) works, however verbose. Full disclosure, I'm only expecting a more 'pythonic' way to do this. It would be nice but unnecessary to have the string format allow for the form b+ax
as opposed to only ax+b
, but this question is out of scope.