Terik Brunson
Terik Brunson

Reputation: 187

Generating 2nd Degree Polynomials from 3-tuples

The purpose of this code is to "Write a function/sub gen_2nd_deg_polys that takes a list of 3-tuples and returns a list of anonymous 2nd degree polynomials." It's telling me that the "function" object has no Getitem attribute.

Am I missing something important about accessing tuples within the lambda?

import sys

def gen_2nd_deg_polys(coeffs):
    return lambda x: (
    str(coeffs[0][0]) + 'x^2 + ' + str(coeffs[0][1]) + 'x + ' + str(coeffs[0][2]) + ' at x = ' + str(x), coeffs[0][0] * x ** 2 + coeffs[0][1] * x + coeffs[0][2])

polys = gen_2nd_deg_polys([(1, 2, 3), (4, 5, 6)])

polys[0](1)
polys[1](2)

Edited... still very wrong

def gen_2nd_deg_polys(coeffs):
    plist = []
    for coeff in coeffs:
        plist.append(lambda x, coeff=coeff:str(coeff[0]) + 'x^2 + ' + str(coeff[1]) + 'x + ' + str(coeff[2]) + ' at x = ' + str(x),  coeff[0] * x**2 + coeff[1] *x + coeff[2])
    return plist

polys = gen_2nd_deg_polys([(1, 2, 3), (4, 5, 6)])
print(polys[0](1))
print(polys[1](2))

Upvotes: 0

Views: 405

Answers (1)

xnx
xnx

Reputation: 25508

You have a number of problems to solve here. Firstly, your gen_2nd_deg_polys function need to loop over your list of tuples and generate a lambda object representing a polynomial from each of them. They can be returned in a list which you can index into (using []) and called (using ()).

A subtle point is that Python binds variable references "late" in lambda definitions (see e.g. here for more on this), so a simple loop like:

for pcoeffs in coeffs:
    plist.append(lambda x: pcoeffs[0] * x**2 + pcoeffs[1] * x + pcoeffs[2])

will cause all your lambdas to use the last tuple of pcoeffs encountered in coeffs (so all your polynomials will be the same). One way around this (the usual one, AFAIK) is to set pcoeffs as a default argument as in the following:

def gen_2nd_deg_polys(coeffs):
    plist = []
    for pcoeffs in coeffs:
        plist.append(lambda x, pcoeffs=pcoeffs: pcoeffs[0] * x**2 + pcoeffs[1] * x + pcoeffs[2])
    return plist

coeffs = [(1,2,3), (0,4,3), (1,5,-3)]

polys = gen_2nd_deg_polys(coeffs)

print polys[0](3), 1*9 + 2*3 + 3
print polys[1](3), 4*3+3
print polys[2](3), 1*9 + 5*3 - 3

Upvotes: 1

Related Questions