Search code examples
pythonpolynomial-math

Calculating polynomials in Python?


I really don't have code to post with this, since I'm pretty stuck on how to write it. I have to give a list of positive ints and an x value to replicate the following example:

>>> poly([1, 2, 1], 2)
9
>>> poly([1, 0, 1, 0, 1], 2)
21
>>> poly([1, 0, 1, 0, 1], 3)
91

The equation I have is p(x) = a0 + a1x + a2x**2 + a3x**3 + ... + anx**n, so an idea I had was checking the length of the list and making it so that it automatically determined how many calculations it had to do, then just replacing x with whatever value was outside the list. Unfortunately I don't know how to write that or where to start really.


Solution

  • def poly(a_list, x):
        ans = 0
        for n,a in enumerate(a_list):
            ans += a*x**n
        return ans
    

    The enumerate function returns a tuple containing the index and value of each element in the list. So you can iterate easily through a list using "for index,value in enumerate(list)".