I want to use the f_i function like this:
for i in range (9):
f_i(y)=c
But I don't know how to use the value of i to call all my ten functions. So what should I do?
Make a list containing the functions and use each function by using loop as follows.
def f1(x):
return x
def f2(x):
return x * 2
def f3(x):
return x * 3
function_list = [f1, f2, f3]
for f in function_list:
print(f(1))
Assume functions is defined/imported into the current file.
locals().get() is the thing that you want
for i in range (9):
func = locals().get("f_{}".format(i))
func(y)
Related
I would like to build the sum of functions in python. However, I don't know upfront the length of the sum. All functions are of similar type, i.e. having one input and same output type. For two something like this would work
In [180]: def H(f, g):
...: def _h(x):
...: return f(x) + g(x)
...: return _h
However, I would like to have something which is generic in the sense that I could write H(*args) and it returns me the sum of all function in args (also working for just one).
Am I correct that this is the only way to build sum of functions? I can't write something like h = f+g for two function ?
It is probably easier to write something that is extendable. And you should use the built-in function sum to do the actual summing. This returns a generator that applies each function to the input x:
def map_funcs(x, *funcs):
return (f(x) for f in funcs)
funcs = lambda x: x + 1, lambda x: x**2
x = 10
print(sum(map_funcs(x, *funcs)))
If you want to you can also make it a wrapper which returns something callable, similar to what you've already got:
def map_funcs(*funcs):
def wrapper(x):
return (f(x) for f in funcs)
return wrapper
funcs = lambda x: x + 1, lambda x: x**2
x = 10
print(sum(map_funcs(*funcs)(x)))
# 111
Yes, it's possible. You have to use the sum() builtin function that return the sum of all values in the given list. Before that, you of course have to compute the list of all the functions givent to H() run with the correct parameter:
def power_two(x):
return x**2
def plus_20(x):
return x + 20
def H(*args):
def _h(x):
_results = [f(x) for f in args]
return sum(_results)
return _h
if __name__ == '__main__':
the_func = H(power_two, plus_20)
final_result = the_func(2)
print("(2^2) + (2+20) = %s" % the_func(2))
print("(3^2) + (3+20) = %s" % the_func(3))
Returns:
(2^2) + (2+20) = 26
(3^2) + (3+20) = 32
Try this:-
def H(*args):
def _h(x):
for func in args:
z += func(x)
return z
return _h
Just loop around the functional arguments and then sum it. I guess simple?
I hope it helps!
I wrote a function "rep" that takes a function f and takes n compositions of f.
So rep(square,3) behaves like this: square(square(square(x))).
And when I pass 3 into it, rep(square,3)(3)=6561.
There is no problem with my code, but I was wondering if there was a way to make it "prettier" (or shorter) without having to call another function or import anything. Thanks!
def compose1(f, g):
"""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h
def rep(f,n):
newfunc = f
count=1
while count < n:
newfunc = compose1(f,newfunc)
count+=1
return newfunc
If you're looking for speed, the for loop is clearly the way to go. But if you're looking for theoretical academic acceptance ;-), stick to terse functional idioms. Like:
def rep(f, n):
return f if n == 1 else lambda x: f(rep(f, n-1)(x))
def rep(f, n):
def repeated(x):
for i in xrange(n):
x = f(x)
return x
return repeated
Using a for loop instead of while is shorter and more readable, and compose1 doesn't really need to be a separate function.
While I agree that repeated composition of the same function is best done with a loop, you could use *args to compose an arbitrary number of functions:
def identity(x):
return x
def compose(*funcs):
if funcs:
rest = compose(*funcs[1:])
return lambda x: funcs[0](rest(x))
else:
return identity
And in this case you would have:
def rep(f,n):
funcs = (f,)*n # tuple with f repeated n times
return compose(*funcs)
And as DSM kindly pointed out in the comments, you could remove the recursion like so:
def compose(*funcs):
if not funcs:
return identity
else:
def composed(x):
for f in reversed(funcs):
x = f(x)
return x
return composed
(also note that you can replace x with *args if you also want to support arbitrary arguments to the functions you're composing, but I left it at one argument since that's how you have it in the original problem)
Maybe someone will find this solution useful
Compose number of functions
from functools import reduce
def compose(*functions):
return reduce(lambda x, y: (lambda arg: x(y(arg))), functions)
Use list comprehensions to generate list of functions
def multi(how_many, func):
return compose(*[func for num in range(how_many)])
Usage
def square(x):
return x * x
multi(3, square)(3) == 6561
I'm very much a beginner, so please be gentle.
I am tinkering with some Python exercises, and I have code looking like this.
def newton(x0, Tol):
def F(x):
return (x**3)+898
def dF(x):
return 3*x**2
x=[x0]
for n in range(400):
x.append(x[n]-(F(x[n]))/dF(x[n]))
if abs((x[n+1])-(x[n]))<Tol:
conv='Converge'
print n
break
if abs((x[n+1])-(x[n]))>=Tol:
conv='No converge'
return x[n+1], conv
I define a function F(x) and its derivative dF(x) and add values to a list x.
The task is to check if the series converge or not, which I think I have succeeded with.
But the question I have is regarding having the functions (x**3)+898 and 3*x**2 as arguments to the function Newton.
I imagined it would be something like this
def newton(f, df, x0, Tol):
def F(x):
return f
def dF(x):
return df
*calculations*
return x[n+1], conv
And you would call it with
newton((x**3)+898, 3*x**2, x0=something, Tol=something)
So that the functions F(x) and dF(x) are defined in the process.
However, x is not defined so it does not work.
Note that having f and df as parameters of 'newton' is required in the excercise.
How would you go about solving this?
Thanks.
You can use lambdas, which are basically simple functions.
You would call it like this:
newton(lambda x: (x**3)+898, lambda x: 3*x**2, x0=something, Tol=something)
This would be the same as doing something like this:
def f1(x):
return (x**3)+898
def f2(x):
return 3*x**2
newton(f1, f2, x0=something, Tol=something)
The only difference is that you don't "give the lambda a name", ie assign it to a variable. This is handy for functions you only need to use once, especially as key arguments to functions like sorted and max.
Use lambda:
newton(lambda x: (x**3)+898, lambda x: 3*x**2, x0=something, Tol=something)
I want to have some sort of reference to a function but I do not know if I need to use a def f(x) or a lambda of some kind.
For instance I'd like to print f(3) and have it output 9a, or is this not how python works?
Second question: Assuming I have a working function, how do I return the degree of it?
To create a function, you define it. Functions can do anything, but their primary use pattern is taking parameters and returning values. You have to decide how exactly it transforms parameters into the return value.
For instance, if you want f(x) to return a number, then a should also be a numeric variable defined globally or inside the function:
In [1]: def f(x):
...: a = 2.5
...: return a * x**2
...:
In [2]: f(3)
Out[2]: 22.5
Or maybe you want it to return a string like this:
In [3]: def f(x):
...: return str(x**2) + 'a'
...:
In [4]: f(3)
Out[4]: '9a'
You have to specify your needs if you need more help.
EDIT: As it turns out, you want to work with polynomials or algebraic functions as objects and do some algebraic stuff with them. Python will allow doing that, but not using standard data types. You can define a class for a polynomial and then define any methods or functions to get the highest power or anything else. But Polynomial is not a built-in data type. There may be some good libraries defining such classes, though.
Python (and most other computer languages) don't do algebra, which is what you'll need if you want symbolic output like this. But you could have a function f(a,x) which returns the result for particular (numerical) values of a:
def f(a, x):
return a*x*x
But if you want a program or language which actually does algebra for you, check out sympy or commercial programs like Mathematica.
If you are just working with polynomials, and you just need a data structure which deals well with them, check out numpy and its polynomial class.
I normally use lambda for short and simple functions:
f = lambda a, x: a * x**2
here a and x are parameters of my function. You need to enter a and x
f(2,4)
If you want a as a constant parameter eg. a=2:
f = lambda x: 2 * x**2
f(5)
if you have a list of input values of x, you can combine map with lambda.
it is straighforward and easily readable.
(*map(lambda x: 3 * x**2, [1,2,3,4]),)
or
list(map(lambda x: 3 * x**2, [1,2,3,4])
cheers!
def func():
print "F(x) = 2x + 3"
x = int(raw_input('Enter an integer value for x: '))
Fx = 2 * x + 3
return Fx
print func()
have fun :)
Cheese,
you can use the def function in Python to create a math function, you could type this:
def f(x):
return(2x + (3 + 3) * 11 + 88) # <- you could make your own function.
print(f(3))
Log:
220
Like THAT
or in this:
def f(a, x):
return((a + x) ** (a * x))
then...
print(f(1, 2))
Log...
6
I was wondering if it is possible in python to do the following:
def func1(a,b):
return func2(c,d)
What I mean is that suppose I do something with a,b which leads to some coefficients that can define a new function, I want to create this function if the operations with a,b is indeed possible and be able to access this outside of func1.
An example would be a simple fourier series, F(x), of a given function f:
def fourier_series(f,N):
...... math here......
return F(x)
What I mean by this is I want to creat and store this new function for later use, maybe I want to derivate it, or integrate or plot or whatever I want to do, I do not want to send the point(s) x for evaluation in fourier_series (or func1(..)), I simply say that fourier_series creates a new function that takes a variable x, this function can be called later outside like y = F(3)... if I made myself clear enough?
You should be able to do this by defining a new function inline:
def fourier_series(f, N):
def F(x):
...
return F
You are not limited to the arguments you pass in to fourier_series:
def f(a):
def F(b):
return b + 5
return F
>>> fun = f(10)
>>> fun(3)
8
You could use a lambda (although I like the other solutions a bit more, I think :) ):
>>> def func2(c, d):
... return c, d
...
>>> def func1(a, b):
... c = a + 1
... d = b + 2
... return lambda: func2(c,d)
...
>>> result = func1(1, 2)
>>> print result
<function <lambda> at 0x7f3b80a3d848>
>>> print result()
(2, 4)
>>>
While I cannot give you an answer specific to what you plan to do. (Looks like math out of my league.)
I can tell you that Python does support first-class functions.
Python may return functions from functions, store functions in collections such as lists and generally treat them as you would any variable.
Cool things such as defining functions in other functions and returning functions are all possible.
>>> def func():
... def func2(x,y):
... return x*y
... return func2
>>> x = func()
>>> x(1,2)
2
Functions can be assigned to variables and stored in lists, they can be used as arguments for other functions and are as flexible as any other object.
If you define a function inside your outer function, you can use the parameters passed to the outer function in the definition of the inner function and return that inner function as the result of the outer function.
def outer_function(*args, **kwargs):
def some_function_based_on_args_and_kwargs(new_func_param, new_func_other_param):
# do stuff here
pass
return some_function_based_on_args_and_kwargs
I think what you want to do is:
def fourier_series(f,N):
#...... math here......
def F(x):
#... more math here ...
import math #blahblah, pseudo code
return math.pi #whatever you want to return from F
if f+N == 2: #pseudo, replace with condition where f,N turn out to be useful
return F
else:
return None
Outside, you can call this like:
F = fourier_series(a,b)
if F:
ans = F(x)
else:
print 'Fourier is not possible :('
The important thing from Python's point of view are:
Yes, you can write a function inside a function
Yes, you can return a function from a function. Just make sure to return it using return F (which returns the function object) as compared to return F(x) which calls the function and returns the value
I was scraping through some documentation and found this.
This is a Snippet Like your code:
def constant(a,b):
def pair(f):
return f(a,b)
return pair
a = constant(1,2) #If You Print variable-> a then it will display "<function constant.
#<locals>.pair at 0x02EC94B0>"
pair(lambda a, b: a) #This will return variable a.
Now, constant() function takes in both a and b and return a function called "Anonymous Function" which itself takes in f, and calls f with a and b.
This is called "closures". Closures is basically an Instance of a Function.
You can define functions inside functions and return these (I think these are technically closures):
def make_f(a, b):
def x(a, b):
return a+b
return x(a, b)