Using regular f (x) function in python

I want to use the f (x) function in python. Something like ax ^ 2 + bx + c (polynomials). I want to do this with a for loop and a list. This is what I have so far:

def f(a,x): for i in range (0, len(a)): i = ([a]*x**i) print (i) 

for example: when I fill in f([5,2,3],5) , I need to get: 3 * 5 ^ 0 + 2 * 5 ^ 1 + 5 * 5 ^ 2. Does anyone know how I can change my code so that the result is the result of this polynomial?

+5
source share
3 answers

Your code is almost correct. You just need to add the current amount and you need to select individual numbers from a

  def f(a,x): running = 0 for i in range (0, len(a)): running += a[-1-i]*x**i return running 
+3
source

use generator expression with enumerate

 >>> sum(data*x**index for index, data in enumerate(reversed(a))) 138 

You can use this understanding in yourself func as follows:

 def f(a,x): print(sum(data*x**index for index, data in enumerate(reversed(a)))) >>> f([5,2,3],5) 138 

EDITED: More optimized version proposed by @Paul Panzer

+4
source

Using loop

 def f(a,x): j = 0 num = 0 for val in a[::-1]:#Reverse a ie [3,2,5] num = num + val*x**jj = j + 1 print(num) f([5,2,3],5) 

Output

 138 
0
source

Source: https://habr.com/ru/post/1273763/


All Articles