Access operator functions by symbol

后端 未结 4 535
臣服心动
臣服心动 2020-12-18 06:18

I need a function which takes one of python\'s operator symbols or keywords as a string, along with its operands, evaluates it, and returns the result. Like

4条回答
  •  甜味超标
    2020-12-18 07:01

    If you're going to use such a map, why not map directly to functions instead of having a layer of indirection by name? For example:

    symbol_func_map = {
        '<': (lambda x, y: x < y),
        '<=': (lambda x, y: x <= y),
        '==': (lambda x, y: x == y),
        #...
    }
    

    While this wouldn't be any more concise than your current implementation, it should get the correct behaviour in the majority of cases. The remaining problems are where a unary and a binary operator conflict, and those could be addressed by adding arity to the dictionary keys:

    symbol_func_map = {
        ('<', 2): (lambda x, y: x < y),
        ('<=', 2): (lambda x, y: x <= y),
        ('==', 2): (lambda x, y: x == y),
        ('-', 2): (lambda x, y: x - y),
        ('-', 1): (lambda x: -x),
        #...
    }
    

提交回复
热议问题