python 2.7 - Generating 2nd Degree Polynomials from 3-tuples -


the purpose of code "write function/sub gen_2nd_deg_polys takes list of 3-tuples , returns list of anonymous 2nd degree polynomials." it's telling me "function" object has no getitem attribute.

am missing important accessing tuples within 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]) + ' @ 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 wrong

def gen_2nd_deg_polys(coeffs):     plist = []     coeff in coeffs:         plist.append(lambda x, coeff=coeff:str(coeff[0]) + 'x^2 + ' + str(coeff[1]) + 'x + ' + str(coeff[2]) + ' @ 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)) 

you have number of problems solve here. firstly, gen_2nd_deg_polys function need loop on list of tuples , generate lambda object representing polynomial each of them. can returned in list can index (using []) , called (using ()).

a subtle point python binds variable references "late" in lambda definitions (see e.g. here more on this), simple loop like:

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

will cause lambdas use last tuple of pcoeffs encountered in coeffs (so polynomials same). 1 way around (the usual one, afaik) set pcoeffs default argument in following:

def gen_2nd_deg_polys(coeffs):     plist = []     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 

Comments