-1

I'm having problems with an exercise in python, I have to create a function that based on a list will give me a certain polynomial equation for example if given [1,2,3] generates x^2 + 2x + 3 and if given [2,2] generates 2x + 2. My idea was to make a function that alters a lambda 1 term at a time as shown bellow but I'm not able to make it work. Any suggestions?

def polynomial(coefs):  
    cofLen = len(coefs)  
    ff = lambda x: 0  
    while cofLen > 0:  
        ff += coefs[0]*( x**cofLen)  
        del coefs[0]  

    return ff  

polynomial([1,2,3])  

The error I get is: NameError: global name 'x' is not defined.

Changing it to

x = 0
def polynomial(coefs):
    global x  
    cofLen = len(coefs)  
    ff = lambda x: 0  
    while cofLen > 0:  
        ff += coefs[0]*( x**cofLen)  
        del coefs[0]  

    return ff  

changes the error to TypeError: unsupported operand type(s) for +=: 'function' and 'int'.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
LValentim
  • 17
  • 1
  • 4
    show your code and error as text – eyllanesc Jan 02 '19 at 16:15
  • what do you mean by generating a polynomial? – Yakov Dan Jan 02 '19 at 16:16
  • What do you expect as the output? – GeeTransit Jan 02 '19 at 16:16
  • Welcome to Stack Overflow! [Please don't post your code as an links or images](//meta.stackoverflow.com/q/285551). It's hard to read, prevents text-based searching, and lowers the overall presentation value of the post. Instead [edit] your post and place your code as text into it se we have a [mcve] to work with. – Patrick Artner Jan 02 '19 at 16:16
  • "polynomial equation" is a vague term. Do you want an expression (string) representing a polynomial? Do you want a polynomial function e.g. `lambda x: x**2+2x+3`? – Acccumulation Jan 02 '19 at 16:22
  • I want the polynomial function. Sorry about the code but when I try to place it in text stackoverflow tells me there's something wrong and doesn't let me post. – LValentim Jan 02 '19 at 16:51
  • 1
    @PatrickArtner I think I fixed it – LValentim Jan 02 '19 at 17:00
  • I added the errors for you. I also cast a reopen vote,if enough vote it will be possible to answer again. – Patrick Artner Jan 02 '19 at 17:10
  • Did the site really say "There is something wrong"? We may need to fix that, then, and change it to clear error mesage. – Jongware Jan 02 '19 at 17:44

1 Answers1

0

You can not extend a lambda like this. The variable you use inside the lambda only exists in it - that is why you get the first error (NameError: global name 'x' is not defined. on x**cofLen)). If you supply a global x, this still wont work, because you can not add an integer to a lambda.

Instead of incrementally building a lambda, you can use a reversed list of coefficients and enumerate() them to get a solution. Enumerate gives you the index into the list which translates to the "power" of x you need. Solution composing the function and calculating one x of it:

def pol(coeff,x): 
    """Calculates the resulting tuple for a polynomial given as coeff list
    anc calculates it at one point of x.

    coeff is a list - most significant exponent first:  [1,2,3] == x^2+2x+3 """

    # create a textual representation
    t = []
    for idx,c in enumerate(coeff[::-1]):
        if c != 0:
            if idx == 0:
                t.append(f"{c}")
            else:
                t.insert(0,f"{f'{c}*' if c != 1 else ''}x{'' if idx==1 else f'^{idx}'}")

    # connect text-parts with '+' and fix '+-' to '-'
    text = '+'.join(t).replace("+-","-")

    # calculate the functions value
    result = sum( x**idx*v for idx,v in enumerate(coeff[::-1]))     

    return  text + f"  (@ x={x}) ",result  

for i in range(10):
     print(*pol([3,1,-4,1,0,-10],i),  sep=" ==> ")

Output:

3*x^5+x^4-4*x^3+x^2-10  (@ x=0)  ==> -10
3*x^5+x^4-4*x^3+x^2-10  (@ x=1)  ==> -9
3*x^5+x^4-4*x^3+x^2-10  (@ x=2)  ==> 74
3*x^5+x^4-4*x^3+x^2-10  (@ x=3)  ==> 701
3*x^5+x^4-4*x^3+x^2-10  (@ x=4)  ==> 3078
3*x^5+x^4-4*x^3+x^2-10  (@ x=5)  ==> 9515
3*x^5+x^4-4*x^3+x^2-10  (@ x=6)  ==> 23786
3*x^5+x^4-4*x^3+x^2-10  (@ x=7)  ==> 51489
3*x^5+x^4-4*x^3+x^2-10  (@ x=8)  ==> 100406
3*x^5+x^4-4*x^3+x^2-10  (@ x=9)  ==> 180863

How does the reverse enumeration work?

enumerate ([3, 1, -4, 1, 0, -10][::-1]) gives us:
# values    -10  0  1 -4  1  3   -> v
# indexes     0  1  2  3  4  5   -> idx

which are then sum( x**idx*v for idx,v in enumerate(coeff[::-1]))-ed.

Example for x==5:

c   idx     v
5 ** 0   * -10 =  -10
5 ** 1   *   0 =    0
5 ** 2   *   1 =   25
5 ** 3   *  -4 = -500
5 ** 4   *   1 =  625
5 ** 5   *   3 = 9375   Total sum = 9515
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69