Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a normal function f(x) in python

Tags:

python

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?

like image 687
Paul Avatar asked Nov 30 '17 10:11

Paul


People also ask

How do you combine two functions in Python?

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.

How do you code a function in Python?

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.


2 Answers

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

like image 169
akash karothiya Avatar answered Oct 17 '22 08:10

akash karothiya


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
like image 28
Paul Panzer Avatar answered Oct 17 '22 07:10

Paul Panzer