Python:实现复杂的字符逻辑运算

时间:2019-05-28 15:44:47

标签: python-3.x

我想做的如下,就像逻辑运算一样:

输入-输出

##input is string and output is character(A or B or C)
## pre-condition: 'A' < 'B' < 'C'

'A and B'                  -->    'B'
'A or B'                   -->    'A'
'A and B and C'            -->    'C'
'(A or B) and C            -->    'C'
'A and (B or C)'           -->    'B'
'(A and B) or (B and C)'    -->    'B'
...
...
...

是否有实现此目标的好主意?谢谢!!!

1 个答案:

答案 0 :(得分:0)

谢谢大家。最后,我使用了复杂的函数来实现它。

代码:

def char_logic_operation(formula_str):
    ## convert str_formula to list, then make a logic operation
    formula_list = re.findall('\([^\)]*\)|\S+', formula_str)
    formula_list = [i.strip('\(\)').split() if re.match('\([ABC] (and|or) [ABC]\)', i) else i for i in formula_list]
    return nesting_list_logic_operation(formula_list)

def nesting_list_logic_operation(n_list):
    #n_list means nesting list
    if any(isinstance(x, list) for x in n_list):
        for i,v in enumerate(n_list):
            if isinstance(v, list):
                n_list[i] = simple_list_logic_operation(v)
        return nesting_list_logic_operation(n_list)
    else:
        return simple_list_logic_operation(n_list)

def simple_list_logic_operation(s_list):
    #s_list means simple list
    if len(s_list) == 1:
        return s_list[0]
    elif len(s_list) >= 3:
        if s_list[1].lower() == 'and':
            res = max(s_list[0], s_list[2])
        elif s_list[1].lower() == 'or':
            res = min(s_list[0], s_list[2])
        del s_list[:3]
        s_list.insert(0, res)
        return simple_list_logic_operation(s_list)

测试:

>>> str1='A and B'
>>> str2='A or B'
>>> str3='A and B and C'
>>> str4='(A or B) and C'
>>> str5='A and (B or C)'
>>> str6='(A and B) or (B and C)'
>>> char_logic_operation(str1)
'B'
>>> char_logic_operation(str2)
'A'
>>> char_logic_operation(str3)
'C'
>>> char_logic_operation(str4)
'C'
>>> char_logic_operation(str5)
'B'
>>> char_logic_operation(str6)
'B'