Python Forum
Create a function vector
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create a function vector
#1
I want to create a function that is modified with a loop and then I can call those different functions from a function vector.
The function to be modified would be the Am function.

The problem is that it only uses the last value of the loop, i=1.
So I have two equal functions, with i=1.
What I want is to have an Am function with i=0, and another with i=1.
Then you can call them from the vector Afunctions

Afunctions = []

def Am(x):
        if((x>xn[i])and(x<=xn[i+1])):
            return (x-xn[i])/h1
        elif((x>xn[i+1])and(x<xn[i+2])):
            return (1-(x-xn[i+1])/h1)
        else:
            return 0

for i in range(0,2,1):
    Afunctions.append(Am) 
Reply
#2
You need to create a function closure. A closure is like a function, but a little bit of context information is kept in the closure. The context information is available to the function when it is executed.

The code below creates a function closure. The function you want to execute is the enclosed function returned by Am. "i" is passed as an argument to Am(), and the value for "i" is kept in the closure so it can be used when you execute the enclosed function. When you execute the enclosed function, the value of "i" is retrieved from the closure.
def Am(i):
    def enclosed(x):
        print(f'i = {i}, x = {x}')

    return enclosed


Afunctions = [Am(i) for i in range(2)]
print(Afunctions[0](2), Afunctions[1](2))
Output:
i = 0, x = 2 i = 1, x = 2
Reply
#3
You can also use partial functions
from functools import partial
 
def am(i, x):
        if xn[i] < x <= xn[i+1]:
            return (x - xn[i]) / h1
        elif xn[i+1] < x <= xn[i+2]:
            return 1 - (x - xn[i+1]) / h1
        else:
            return 0

 afunctions = [partial(am, i) for i in range(2)]
Reply
#4
Or a lambda expression.
def Am(x, i):
    print(f'i = {i}, x = {x}')

Afunctions = [lambda x, index=i: Am(x, index) for i in range(2)]
print(Afunctions[0](2), Afunctions[1](2))
Output:
i = 0, x = 2 i = 1, x = 2
Reply
#5
Thank you guys , i appreciate your effort and speed to answer.!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  substring function to create new column Chandan 6 2,510 Feb-14-2020, 10:11 AM
Last Post: scidam
  matrix by vector mcgrim 8 3,879 May-02-2019, 10:39 AM
Last Post: ichabod801
  How to create a random library for an specific function andre_fermart 4 3,351 Apr-10-2019, 11:02 PM
Last Post: andre_fermart
  Vector field cross product Eduard 2 2,574 Aug-20-2018, 02:54 PM
Last Post: Eduard

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020