Evaluating Polynomial coefficients

后端 未结 5 1875
甜味超标
甜味超标 2020-12-18 13:07

I\'m trying to write a function that takes as input a list of coefficients (a0, a1, a2, a3.....a n) of a polynomial p(x) and the value x. The function will return p(x), whic

5条回答
  •  青春惊慌失措
    2020-12-18 13:24

    simple:

    def poly(lst, x): 
      n, tmp = 0, 0
      for a in lst:
        tmp = tmp + (a * (x**n))
        n += 1
    
      return tmp
    
    print poly([1,2,3], 2)
    

    simple recursion:

    def poly(lst, x, i = 0):
      try:
        tmp = lst.pop(0)
      except IndexError:
        return 0
      return tmp * (x ** (i)) + poly(lst, x, i+1)
    
    print poly([1,2,3], 2)
    

提交回复
热议问题