0

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.

2 Answers2

1

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.

1

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
Finn
  • 326
  • 3
  • 11