rahram
rahram

Reputation: 590

how to get a function from input and apply it on data in python

It is normal to get arguments, numbers, and strings from input in python. I am wondering if there is a way to get a user-defined function from the input and apply it in my program.

Suppose I have a program

a = [12,34,2,3,4,23,16,84,3]
print(a)
b = get_function_from_input()
print(b(a))

and if a user inserts something like following in input:

def myfun(X):
   return([max(X),min(X),sum(X)])

then my program outputs:

[84,2,181]  

Upvotes: 2

Views: 1025

Answers (2)

Jay Calamari
Jay Calamari

Reputation: 653

How are you getting the input exactly?

If it helps, just want to point out that functions, like numbers and strings, are objects in python, and can be treated as parameters or return values.

a = [12,34,2,3,4,23,16,84,3]

def dostuff(func):
    return func(a)

def myfun(X):
    return([max(X),min(X),sum(X)])

print(dostuff(myfun))

outputs

[84, 2, 181]

Upvotes: 1

jpp
jpp

Reputation: 164783

You can use a dictionary to link to logic already defined:

a = [12,34,2,3,4,23,16,84,3]

def myfun(X):
    return([max(X),min(X),sum(X)])

dispatcher = {'max_min_sum': myfun}

b = input('Enter a dispatcher key:\n')

print(dispatcher[b](a))

Demo input / output:

Enter a dispatcher key:
max_min_sum
[84, 2, 181]

Upvotes: 3

Related Questions