Runtime evaluation/In an environment: Difference between revisions

→‎{{header|Python}}: swapped introspection for another way to use more than one variable
(→‎{{header|Python}}: alternate implementation using compile & introspection)
(→‎{{header|Python}}: swapped introspection for another way to use more than one variable)
Line 48:
=={{header|Python}}==
 
<lang python>>>> def eval_with_x(code, =a, raw_input('f(xb): ')
return eval(funccode, name[1]{'x':b}) - eval(funccode, name[0]{'x':a})
x = [input('x[%i]: ' % i) for i in [0,1]]
fx = [eval(code, {"x": xv}) for xv in x]
print "f({x[0]}) = {f0}; f({x[1]}) = {f1}; f({x[1]}) - f({x[0]}) = {ans}".format(
x=x, f0=fx[0], f1=fx[1], ans= fx[1] - fx[0] )</lang>
 
>>> eval_with_x('2 ** x', 3, 5)
Typical use would be <small>(user input is after the initial colon in a line)</small>:
24</lang python>f(x): 2**x
x[0]: 3
x[1]: 5
f(3) = 8; f(5) = 32; f(5) - f(3) = 24</lang>
 
===Python: usingfor introspectionmultiple names===
A slight change allows the evaluation to take multiple names:
In Python, one can compile an expression then query the compiled object to find out the names that are used. This second example uses this method:
<lang python>func>>> =def compileeval_with_args(code, raw_input('Enter expression**kwordargs): '),
return eval(code, kwordargs)
'compile_error.txt',
'eval' )
# ask for two sets of any names used in the expression
name = [{}, {}]
for n in func.co_names: name[0][n] = input('First value of %s: ' % n)
for n in func.co_names: name[1][n] = input('Second value of %s: ' % n)
 
>>> code = '2 ** x'
print "\n<Expression at second value set> - <Expression at first> =", \
>>> eval_with_args(code, x=5) - eval_with_args(code, x=3)
eval(func, name[1]) - eval(func, name[0])
24
</lang>
>>> code = '3 * x + y'
A simple use would be:
>>> eval_with_args(code, x=5, y=2) - eval_with_args(code, x=3, y=1)
<lang python>Enter expression: 2**x
7
First value of x: 3
>>> </lang>
Second value of x: 5
 
<Expression at second value set> - <Expression at first> = 24</lang>
and for an initial expression using multiple variables:
<lang python>Enter expression: 3 * x + y
First value of x: 1
First value of y: 2
Second value of x: 3
Second value of y: 4
 
<Expression at second value set> - <Expression at first> = 8</lang>
 
=={{header|Ruby}}==
Anonymous user