3

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.

Eric
  • 95,302
  • 53
  • 242
  • 374
user1505713
  • 615
  • 5
  • 20

4 Answers4

3

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
Kevin
  • 74,910
  • 12
  • 133
  • 166
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
Eric
  • 95,302
  • 53
  • 242
  • 374
0

If you really want your output to look great, like this is for a paper you want to publish or something, you can output LaTeX that typesets your equation.

http://oneau.wordpress.com/2011/12/25/latex-sympy/

Print latex-formula with python

Also, do you know about the Sage math tool? It combines Python with numerous math libraries. If you use Sage, you can work with symbolic equations and your "workbooks" will show the equations rendered by TeX. Sage uses a subset of TeX written in JavaScript to typeset your equations! Note: Sage made the choice to use the ^ operator for exponentiation, as you are doing in your example. In Sage you can type equations using ^ rather than **.

http://www.sagemath.org/doc/tutorial/tour_algebra.html

http://sagemath.org/

Community
  • 1
  • 1
steveha
  • 74,789
  • 21
  • 92
  • 117
0
import re

expressions = ["2x^3+3x^2-6x+1", "30.1x^2+60.2x-90.3", "x^2+2x+1"]

for i in expressions:
  print re.sub('.', lambda m: {'+':' + ', '-':' - '}.get(m.group(), m.group()), i)
alvas
  • 115,346
  • 109
  • 446
  • 738