Demo entry 6677223

sdf

   

Submitted by anonymous on Dec 03, 2017 at 08:27
Language: Python 3. Code size: 2.7 kB.

# -*- coding: utf-8 -*-
import copy
from prettytable import PrettyTable
lst = ['a','b','c','d','e','#']
Ad = {}
Bd = {}
Cd = {}
Dd = {}

String = list(input("字符串: "))
String.append('#')

#作为最终结果的输出表格
Table = PrettyTable(["状态栈", "符号栈", "剩余串"])
Table.align["状态栈"] = 'l'
Table.align["符号栈"] = 'l'
Table.align["剩余串"] = 'l'
Table.padding_width = 0
Table.header = True

table = PrettyTable(["Action","Goto"])
table.align["Action"] = 'l'
table.align["Goto"] = 'l'
table.padding_width = 0

for item in lst:
    Ad[item] = 'r2'
    Bd[item] = 'r3'
    Cd[item] = 'r4'
    Dd[item] = 'r1'

Action = {0:{'a':'S2'},
          1:{'#':'acc'},
          2:{'b':'S4'},
          3:{'c':'S5','b':'S6'},
          4:Ad,
          5:{'d':'S8'},
          6:Bd,
          7:{'e':'S9'},
          8:Cd,
          9:Dd}

Goto = {0:{'S':1},2:{'A':3},5:{'B':7}}

GS = {1:['S','aAcBe'],2:['A','b'],3:['A','Ab'],4:['B','d']}

State = [0]
Symbol = ['#']
action=['-']

s1 = ''.join(map(str,copy.deepcopy(State)))
sy1 = ''.join(copy.deepcopy(Symbol))
ss1 = ''.join(copy.deepcopy(String))
Table.add_row([s1,sy1,ss1])


def LR():
    while action[-1] != 'acc':
        if 'S' in Action[int(State[-1])][String[0]]:
            action[0] = copy.deepcopy(Action[int(State[-1])][String[0]])
            table.add_row([action[0],' '])
            State.append(Action[int(State[-1])][String[0]][-1])
            st = ''.join(map(str,copy.deepcopy(State)))
            Symbol.append(String[0])
            sy = ''.join(copy.deepcopy(Symbol))
            String.pop(0)
            stri = ''.join(copy.deepcopy(String))
            Table.add_row([st,sy,stri])
            
        elif 'r' in Action[int(State[-1])][String[0]]:
            action[0] = copy.deepcopy(Action[int(State[-1])][String[0]])
            R = len(GS[int(Action[int(State[-1])][String[0]][-1])][1])
            poper = int(State[-1])
            for i in range(0,R):
                State.pop()
                Symbol.pop()
            Symbol.append(GS[int(Action[poper][String[0]][-1])][0])
            sym = ''.join(copy.deepcopy(Symbol))
            table.add_row([action[0],Goto[int(State[-1])][Symbol[-1]]])
            State.append(Goto[int(State[-1])][Symbol[-1]])
            stat = ''.join(map(str,copy.deepcopy(State)))
            strgx = ''.join(copy.deepcopy(String))
            Table.add_row([stat,sym,strgx])
        else:
            action[0] = copy.deepcopy(Action[int(State[-1])][String[0]]) #aciton表示最后的acc
            table.add_row([action[0],' ']) #插入表格
    print(Table)
    print(table)
if __name__ == "__main__":
    LR()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).