エクスプレッション計算-Phython版

3652 ワード

再帰的な方法を用いて一般式の値を解く
原理の概略:
式:アイテム+または-[アイテム]...アイテム:ファクタ*または/[ファクタ]...ファクタ:式または整数(再帰終点)
注:以上のコンパイル原理に似た文法解析のバコスパターン(BNF)によると、冒頭の右側は左側、つまり左側は右側に展開できる形式で、これ以上展開できないことを知っている(終端に遭遇)

index = 0

def expValue(exp):
    global index
    result = termValue(exp)
    more = True
    while more:
        #index += 1
        op = exp[index]
        if op in '+-':
            index += 1
            value = termValue(exp)
            if op == '+':
                result += value
            else:
                result -= value
        else:
            more = False
    return result

def factorValue(exp):
    global index
    result = 0
    c = exp[index]
    if c == '(':
        index += 1
        result = expValue(exp)
        index += 1
    else:
        while c.isdigit():
            result = 10 * result + int(c) - 0
            index += 1
            c = exp[index]
    return result

def termValue(exp):
    global index
    result = factorValue(exp)
    while True:
        op = exp[index]
        if op in '*/':
            index += 1
            value = factorValue(exp)
            if op == '*':
                result *= value
            else:
                result /= value
        else:
            break
    return result

def main():
    exp = '1+3*(3+1)*4+(1+5)#'
    result = expValue(exp)
    print('EXP : %d' % result)
    print('Compute Ok!')

if __name__ == '__main__':
    main()

注意:1、式文字列の最後に#文字を付けて、式の終わりを判断します2、式の要素の間にスペースを使うことができなくて、類似の語法を使って式の各Tokenの改善を分析することができます