What format string would I use to print expressions like
2x^3 + 3x^2 - 6x + 1 (notice spaces on either side of signs)
30.1x^2 + 60.2x - 90.3
and (if straightforward)
x^2 + 2x + 1 (no coefficient on terms in x if coefficient is 1).
I've tried inserting padding between a forced sign like this:
"{0: =+}x^2 {1: =+}x {2: =+}".format(1, -2, 3)
but no padding appears.
Since you didn't specify, I assume that your expressions are already in string form and you only need to make them look better. In that case, adding spaces on either side of signs can be done with a simple replace call.
def add_spaces_to_either_side_of_signs(s):
return s.replace("+", " + ").replace("-", " - ")
expressions = [
"2x^3+3x^2-6x+1",
"30.1x^2+60.2x-90.3",
"x^2+2x+1"
]
for expression in expressions:
print "non-pretty version:", expression
print "pretty version: ", add_spaces_to_either_side_of_signs(expression)
Result:
non-pretty version: 2x^3+3x^2-6x+1
pretty version: 2x^3 + 3x^2 - 6x + 1
non-pretty version: 30.1x^2+60.2x-90.3
pretty version: 30.1x^2 + 60.2x - 90.3
non-pretty version: x^2+2x+1
pretty version: x^2 + 2x + 1
Assuming you have [1, -6, 3, 2] representing "2x^3 + 3x^2 - 6x + 1":
class Polynomial(list):
def __repr__(self):
# joiner[first, negative] = str
joiner = {
(True, True): '-',
(True, False): '',
(False, True): ' - ',
(False, False): ' + '
}
result = []
for power, coeff in reversed(list(enumerate(self))):
j = joiner[not result, coeff < 0]
coeff = abs(coeff)
if coeff == 1 and power != 0:
coeff = ''
f = {0: '{}{}', 1: '{}{}x'}.get(power, '{}{}x^{}')
result.append(f.format(j, coeff, power))
return ''.join(result) or '0'
>>> Polynomial([1, -6, 3, 2])
2x^3 + 3x^2 - 6x + 1
>>> Polynomial([1, -6, 3, -2])
-2x^3 + 3x^2 - 6x + 1
>>> Polynomial([])
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With