sampleuser
sampleuser

Reputation: 320

Python: String formatting together with enumerate? (Producing a nice string representation of a polynomial in a pythonic way)

I started to write a little class that should represent polynomial functions in one variable. I'm aware that the powerful sympy module is out there but I decided that it is simpler to put a few lines of code instead of loading the entire sympy module. The main reason is that simply just uses a level of abstraction (i.e. dealing with variables and rings) that I don't need.

So here is what I did:

class Polynomial:
    """Class representing polynomials."""
    
    def __init__(self, *coefficients):
        self.coefficients = list(coefficients)
        """Coefficients of the polynomial in the order a_0,...a_n."""
     
    def __repr__(self):
        return "Polynomial(%r)" % self.coefficients
            
    def __call__(self, x):    
        res = 0
        for index, coeff in enumerate(self.coefficients):
            res += coeff * x** index
        return res

I would like to also implement __str___ with the same output as produced by the for loop:

res = ""
for index, coeff in enumerate(self.coefficients):
    res += str(coeff) + "x^"+str(index)

First, I expected something like "$r*x^%r" % enumerate(self.coefficients) to work but it doesn't. I tried to convert the enumerate(...) to tuple but this also didn't solve the problem.

Any ideas for a pythonic, one-line return statement I could use for __str__?

Upvotes: 1

Views: 46

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

I'm not sure if I've understood your question correctly, but you can use str.format with str.join to obtain your string. For example:

coefficients = [2, 5, 1, 8]
print( '+'.join('{1}*x^{0}'.format(*v) for v in enumerate(coefficients)) )

Prints:

2*x^0+5*x^1+1*x^2+8*x^3

Upvotes: 1

Related Questions