I want to use a function f(x) in python. Something like ax^2 + bx + c (polynomials). I want to do that using 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 have to get:
3*5^0 + 2*5^1 + 5*5^2. Does somebody know how I can change my code so the output will be the result of that polynomial?
We can create a special function which can combine any two functions. We can compose any number of function by modifying the above method. Now we will modify our composite_function to a function that can compose any number of function instead of two by using reduce() function from functools library.
Basic Syntax for Defining a Function in Python In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon. The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.
use a generator expression
with enumerate
>>> sum(data*x**index for index, data in enumerate(reversed(a)))
138
You can use this comprehension in you func
like this :
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 suggested by @Paul Panzer
Your code is almost correct. You just need to add a running sum, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With