Thursday 15 January 2015

Distribution of Function over Arithmetic Operations in Python -


Let's have a mapping, map, that connects different stars with numeric values:

  I want to define an operation,  op    code>, which will deliver arithmetic operations. So I want the op to work:  
  op ('a + b') = 3 op ('b') = 2 op ('a * b + c') = 7   

etc.

The only way I can think of doing this is to parse the string, remember operation, mapping and operation is very expensive / long and I hope that with an inbuilt operation There can be a more elegant solution.

Edit:

I realized that the way I did not clear this was accurate for my question, mapping is not defined on my system, so I defined all possible mapping I can not ask mapping for the source outside

'It is not sure that you are in meditation But Python allows you to parse a string if it is not desirable, you can use a Create Apr class can define operators related to extract values ​​from the "mapping". Here, I use a dictionary and I only define "besides":

  class V: values ​​= {'a': 1, 'b': 2 , 'C': 3} def __int __ (self, name): self. Name = name def __add __ (self, other): Return V.values ​​[self.name] + V.values ​​[other.name] a = V ('a') b = V ('B' print If you work with strings, you can also print this type of expression (even if  eval  is not your best friend) print A + B # display 3   

A security point of view - you should never have any expressions coming from eval untrusted source):

  print eval ("a + B ") # Display 3    

No comments:

Post a Comment