Python: Indices of identical tuple elements are also identical? -
just starting out apologize if stupid question. python 2.7 if it's important. i'm writing program evaluates polynomial coefficients represented elements of tuple @ x power index of coefficient. runs fine when coefficients different, issue i'm having when of coefficients same. code below -
def evaluate_poly(poly, x): """polynomial coefficients represented elements of tuple. each coefficient evaluated @ x ** index of coefficient""" poly_sum = 0.0 coefficient in poly: val = coefficient * (x ** poly.index(coefficient)) poly_sum += val return poly_sum poly = (1, 2, 3) x = 5 print evaluate_poly(poly, x) ##for coefficient in poly: ##print poly.index(coefficient)
which returns 86 expect.
the commented out print statement return indices of each element in poly. when they're different (1, 2, 3) returns expect (0, 1, 2) if of elements same (1, 1, 2) indices same (0, 0, 1), i'm able evaluate polynomials coefficients different. doing wrong here? figure has -
poly.index(coefficient)
but can't figure out why exactly. in advance
use enumerate, index index of first occurrence repeated elements fail, in code poly.index(1)
using (1, 1, 2)
going return 0
each time:
uusing enumerate give each actual index of every element , more efficiently:
def evaluate_poly(poly, x): """polynomial coefficients represented elements of tuple. each coefficient evaluated @ x ** index of coefficient""" poly_sum = 0.0 # ind each index, coefficient each element ind, coefficient in enumerate(poly): # no need val += coefficient * (x ** ind) poly_sum += coefficient * (x ** ind) return poly_sum
if print(list(enumerate(poly)))
see each element , it's index in list:
[(0, 1), (1, 1), (2, 3)]
so ind
each time in loop refers index of each coefficient
in poly list.
you can return generator expression using sum:
def evaluate_poly(poly, x): """polynomial coefficients represented elements of tuple. each coefficient evaluated @ x ** index of coefficient""" return sum((coefficient * (x ** ind) ind, coefficient in enumerate(poly)),0.0)
using 0.0
start value mean float returned opposed int. cast float(sum...
think simpler pass start value float.
Comments
Post a Comment