Skip to content

Commit

Permalink
Update the definition of DFA and part of the function of NFA to DFA t…
Browse files Browse the repository at this point in the history
…ransformation
  • Loading branch information
dejavudwh committed Sep 21, 2019
1 parent 376a497 commit d96e29e
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 1 deletion.
Empty file added dfa/__init__.py
Empty file.
45 changes: 45 additions & 0 deletions dfa/construction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from parse.parse import (
closure,
move,
)
from dfa.dfa import (
Dfa,
MAX_DFA_STATUS_NUM,
)
from nfa.nfa import ASCII_COUNT
from utils import list_dict


def convert_to_dfa(nfa_start_node):
jump_table = list_dict(MAX_DFA_STATUS_NUM)
dfa_list = []
n_closure = closure(nfa_start_node)
dfa = Dfa.nfas_to_dfa(n_closure)
dfa_list.append(dfa)

dfa_index = 0
while dfa_index < len(dfa_list):
dfa = dfa_list[dfa_index]
for i in range(ASCII_COUNT):
c = chr(i)
nfa_move = move(dfa.nfa_sets, c)
if nfa_move is not None:
nfa_closure = closure(nfa_move)
new_dfa = convert_completed(dfa_list, nfa_closure)
if new_dfa is None:
new_dfa = Dfa.nfas_to_dfa(nfa_closure)
dfa_list.append(new_dfa)
next_state = new_dfa.status_num
jump_table[dfa.status_num][c] = next_state
dfa_index = dfa_index + 1

return jump_table



def convert_completed(dfa_list, closure):
for dfa in dfa_list:
if dfa.nfa_sets == closure:
return dfa

return None
22 changes: 22 additions & 0 deletions dfa/dfa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MAX_DFA_STATUS_NUM = 256


class Dfa(object):
STATUS_NUM = 0

def __init__(self):
self.nfa_sets = set()
self.accepted = False
self.status_num = -1

@classmethod
def nfas_to_dfa(cls, nfas):
dfa = cls()
for n in nfas:
dfa.nfa_sets.append(n)
if n.next_1 is None and n.next_2 is None:
dfa.accepted = True

dfa.status_num = Dfa.STATUS_NUM
Dfa.STATUS_NUM = Dfa.STATUS_NUM + 1
return dfa
1 change: 0 additions & 1 deletion nfa/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,6 @@ def nfa_set_nega_char(pair_out):
char_set_inversion(start.input_set)

lexer.advance()

return True


Expand Down
4 changes: 4 additions & 0 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ def log(*args, **kwargs):
value = time.localtime(int(time.time()))
dt = time.strftime(format, value)
print(dt, *args, **kwargs)


def list_dict(width):
return [dict() for i in range(width)]

0 comments on commit d96e29e

Please sign in to comment.