-
Notifications
You must be signed in to change notification settings - Fork 0
/
BASIC NFA
51 lines (41 loc) · 1.53 KB
/
BASIC NFA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class NFA:
def __init__(self):
self.states = {'q0', 'q1', 'q2'}
self.alphabet = {'0', '1'}
self.transitions = {
'q0': {'0': {'q0', 'q1'}, '1': {'q0'}},
'q1': {'1': {'q2'}},
'q2': {}
}
self.start_state = 'q0'
self.accept_states = {'q2'}
def epsilon_closure(self, states):
stack = list(states)
closure = set(states)
while stack:
state = stack.pop()
if '' in self.transitions[state]:
for next_state in self.transitions[state]['']:
if next_state not in closure:
closure.add(next_state)
stack.append(next_state)
return closure
def process_input(self, input_string):
current_states = self.epsilon_closure({self.start_state})
for char in input_string:
next_states = set()
for state in current_states:
if char in self.transitions[state]:
next_states.update(self.transitions[state][char])
current_states = self.epsilon_closure(next_states)
return any(state in self.accept_states for state in current_states)
def accepts(self, input_string):
return self.process_input(input_string)
# Testing the NFA
nfa = NFA()
# Test strings
test_strings = ['01', '10', '001', '101', '111', '0001']
# Test and print results
for string in test_strings:
result = nfa.accepts(string)
print(f"String '{string}' accepted? {result}")