0

Problem: Write a function to let the user calculate the value of a function f(x) at an arbitrary point x = a

  • Input: a
  • Output: value of the function f at x = a

Apply to calculate the value of f(x)= sqrt(x-2) at x=4.

My question: I don't know clearly the meaning of this problem. If we want to calculate the value of a function, we can assign a value we need and put it in a function without defining a function like this?

0

2 Answers 2

2

Yes. You can use something like eval. You don't actually need to define a function in your code. Instead, you can put it in a string and pass it to eval.

Try something like this:

import math

a = int(input())
f = 'math.sqrt(x-2)'
x = a

print(eval(f))

You could change f to any function, or even read f from input as a string.

3
  • I think like the way you comment here but the requirements of the problem make me confused. Commented Jun 12, 2022 at 16:14
  • 1
    I see. I assumed your question was why not just define some function f as math.sqrt(x-2), and so I supplied this answer as an alternative.
    – Ryan Zhang
    Commented Jun 12, 2022 at 16:16
  • 1
    Under the constraints of the problem as you've described it, I think you can just define some f and pass a to it, just print out f(a)
    – Ryan Zhang
    Commented Jun 12, 2022 at 16:16
1

You have a as input and f(a) as output, but the problem says define a function to apply f on a. So, instead of directly writing f(a) you write eval_func(a) that returns the same f(a).

import math 

def eval_func(a):
    x = a
    return math.sqrt(x-2)

Run with input 4:

eval_func(4)
1.4142135623730951

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.