Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

z3python: converting string to expression

Tags:

python

z3

Given that x,y,z = Ints('x y z') and a string like s='x + y + 2*z = 5', is there a quick way to convert s into a z3 expression ? If it's not possible then it seems I have to do lots of string operations to do the conversion.

like image 404
Vu Nguyen Avatar asked Sep 22 '12 02:09

Vu Nguyen


People also ask

How do you convert a string to an expression?

Convert a String to an Expression in R Programming – parse() Function. parse() function in R Language is used to convert an object of character class to an object of expression class.

How do you convert a string to an expression in Python?

You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.


1 Answers

You can use the Python eval function. Here is an example:

from z3 import *
x,y,z = Ints('x y z') 
s = 'x + y + 2*z == 5'
F = eval(s)
solve(F)

This script displays [y = 0, z = 0, x = 5] on my machine.

Unfortunately, we can't execute this script at http://rise4fun.com/z3py. The rise4fun website rejects Python scripts containing eval (for security reasons).

like image 199
Leonardo de Moura Avatar answered Oct 17 '22 09:10

Leonardo de Moura