Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested functions in python: Polynomial exercise

Context: I’m trying to make make a function that will return the value of any given polynomial. So for polynomial(a), where a = [a0,a1,…,an] should return a function p so that p(x) is the polynomial a0x**n + a1x**(n-1)…+an.

This is what I have:

def polynomial(coefs):
    
    def p(x):
        res = 0
        i = len(coefs)
        for a in coefs[:-1]:
            i -=1
            res += a*x**i
        res += coefs[-1]
        return res
    return p(x)
        
# Tests:
xx = [0, 1, 2, 3]   # Valores de x a testar
r = polynomial([1, 2, 3])   
print([r(x) for x in xx])   # should return [3, 6, 11, 18]

But I keep getting name 'x' is not defined. If I’m saving the polynomial function as r, then if we pass an argument such as r(2) shouldn’t it basically return p(2) which will in turn return the result?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you in advance! Any help is welcome as I’m still learning python

Note: I’m aware the function isn’t perfect yet for the example I’m trying to achieve, but I’d simply like to retrieve the desired output first and then I’ll check the inner workings of the p(x) function again

>Solution :

You actually can simplify this using lambda expression, and end up with something like this

from typing import List, Callable


def polynomials(coefs: List[int]) -> Callable[[int], int]:
    return lambda x: sum([coefs[len(coefs) - i - 1] * (x ** i) for i in range(len(coefs) - 1, -1, -1)])


function = polynomials([1, 2, 3])  # x^2 + 2x + 3

print(function(1))  # 6
print(function(2))  # 11
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading