5

I was trying to solve UVA 11036. It requires defining function at runtime.

For Example: I have to take input (2*x + 7) % N as a string and define a function at runtime like func = lambda x : (2*x + 7) % N to work on it. Please help me to find out how to convert string to function at runtime.

3
  • 3
    Please explain how this is related to C++. Commented Aug 20, 2020 at 6:29
  • 1
    Use exec() to execute a statement in a string. Commented Aug 20, 2020 at 6:31
  • 2
    That problem doesn't require defining a function from a string. You should parse the RPN and generate a function dynamically using functional composition. Commented Aug 20, 2020 at 6:33

2 Answers 2

8

It seems captivating riddle, so if you want to solve it in C++ have two way. The hard way is implementing a small math parser using some algorithms like Shunting-yard algorithm. Or instead of, if you are familiar with library linking in C++, it is better to use a mathematical expression parser libraries. There are many libraries on Internet. Here, I suggest one of them as below.

mathematical expression library I personalty have tested it and obviously is fast. you can clone source code in GitHub

Anyway, you can not solve this case with lambda functions because, the input is a mathematical expression you should parse and calculate it runtime.

if you use python see this post.

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

2 Comments

@rioV8 Yes it is that.
0

You could use exec to define a function from a string. However that allows to inject any code into your program. But as it's only for solving that challenge, it might be fine.

exec 'func = lambda x : '+input

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.