0

Say I have the following example, in python:

import numpy as np, PROGRAMS as prg
testlist = []
x = 0
n=0
y=[1,2,3,4,5]
x_fn = np.array=([prg.test1(x),prg.test2(x),prg.test3(x)])

for i in range(0,len(x_fn)):
    for j in range(0, len(y)):

        x = y[j]*2
        z=x_fn[i]

        testlist.append(z)
        j = j+1
i = i+1

print testlist

#####PROGRAMS
def test1(x):
    x=x**2

    return x

def test2(x):
    x=x**3

    return x

def test3(x):
    x=x+10

    return x

If x isn't defined before x_fn then an error occurs but if I define it as zero then that is what is used in the calculations. I basically want this code to produce a list with the the defined value of x in the 2nd loop :

x = y[j]*2

for all values of y. I know there would be a way around this mathematically - but I would like to solve it by running the same function and not changing any of the values of y or any of the functions in PROGRAMS.

Basically, is it a good idea to put these functions in a array and run through it element by element or is there a better way to do it?

Thanks in advance for your replies,

Sven D.

2 Answers 2

1

Could this be what you want ?

def test1(x):
    x=x**2

    return x

def test2(x):
    x=x**3

    return x

def test3(x):
    x=x+10

    return x


testlist = []
n=0
y_vals=[1,2,3,4,5]

x_fn = [test1, test2, test3]

for fun in x_fn:
    for y in y_vals:

        x = y*2
        z=fun(x)

        testlist.append(z)

print testlist

Functions are objects that can be stored in containers and recalled for use later just like any other object in Python.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply -this looks like this exactly what I want - thankyou!
0

You don't even need to use numpy arrays. Just use a list (functions) and put the test functions in it. Note, that I have removed the argument. The elements of the functions array are references to the functions, so you can use them in your loop.

import PROGRAMS as prg

testlist = []
y=[1,2,3,4,5]
functions = [prg.test1, prg.test2, prg.test3]

for func in functions:
    for j in y:
        x = j*2
        z = func(x)
        testlist.append(z)

print testlist

#####PROGRAMS
def test1(x):
    x=x**2

    return x

def test2(x):
    x=x**3

    return x

def test3(x):
    x=x+10

    return x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.