3
d = ['X + Y = Z', 'X <=Y']
p = [{'Y': 1, 'X': 0, 'Z': 0}, {'Y': 1, 'X': 0, 'Z': 3}, {'Y': 1, 'X': 0, 'Z': 6}, {'Y': 1, 'X': 0, 'Z': 9}, {'Y': 1, 'X': 1, 'Z': 0}, {'Y': 1, 'X': 1, 'Z': 3}]

I need to create create some structure which would store List of expressions, where variables are changed.

I need to know: X, Y, Z current values expressions with changed letters to integers

and it has to be for each dict of values

The problem is to see for what X,Y,Z, all expressions are True

matiit
  • 7,969
  • 5
  • 41
  • 65
  • 1
    possible duplicate of [Evaluating mathematical expressions in Python](http://stackoverflow.com/questions/5049489/evaluating-mathematical-expressions-in-python) – outis Dec 17 '11 at 19:35
  • This is certanly **not** a duplicate of the linked question. – Steinar Lima Mar 28 '14 at 12:04

2 Answers2

3

According the expressions are made by you (so you can trust them), a simple solution is to use eval() like this :

correct_values = []
for value in p:
    #if eval(d[0], value) and eval(d[1], value):   # basic version
    if all(eval(exp, value) for exp in d):       # ehanced version thanks to @isbadawi
       correct_values.append(value)

but you'll have to correct the expression X + Y = Z is not valid python, X + Y == Z is a valid python expression.

But with the values you gave in example, nothing is matching :(

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
  • I know eval and i am going to use that.There could be more than 2 expressions so your approach isn't good i think :( And I pasted just several values :) – matiit Dec 17 '11 at 19:39
  • 2
    It's easy to generalize to more than two: `if all(eval(exp, value) for exp in d):` – Ismail Badawi Dec 17 '11 at 19:46
0

I would've opted for a more secure solution than using eval:

p = [{'Y': 1, 'X': 0, 'Z': 0}, {'Y': 1, 'X': 0, 'Z': 3},
     {'Y': 1, 'X': 0, 'Z': 6}, {'Y': 1, 'X': 0, 'Z': 9},
     {'Y': 1, 'X': 1, 'Z': 0}, {'Y': 1, 'X': 1, 'Z': 3}]

f = lambda v: all([v['X'] + v['Y'] == v['Z'],
                   v['X'] <= v['Y'],
                   2*v['X'] + v['Y'] < v['Z']])

print [f(k) for k in p]

# Output: [False, False, False, False, False, False]
Steinar Lima
  • 7,644
  • 2
  • 39
  • 40