Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions project/to_finite_automaton_converters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from sys import stderr
from typing import Set

from networkx import MultiDiGraph
from pyformlang.regular_expression import Regex
from pyformlang.finite_automaton import (
DeterministicFiniteAutomaton,
NondeterministicFiniteAutomaton,
)


def regex_to_dfa(regex: str) -> DeterministicFiniteAutomaton:
r = Regex(regex)
nfa = r.to_epsilon_nfa()
if nfa is None:
print("Failed to convert regex to automaton", file=stderr)
return DeterministicFiniteAutomaton()
dfa = nfa.to_deterministic().minimize()
return dfa


def graph_to_nfa(
graph: MultiDiGraph, start_states: Set[int], final_states: Set[int]
) -> NondeterministicFiniteAutomaton:
a = NondeterministicFiniteAutomaton.from_networkx(graph)
match len(start_states):
case 0:
for v in graph.nodes:
a.add_start_state(v)
case _:
for s in start_states:
a.add_start_state(s)
match len(final_states):
case 0:
for v in graph.nodes:
a.add_final_state(v)
case _:
for f in final_states:
a.add_final_state(f)
return a.remove_epsilon_transitions()
2 changes: 1 addition & 1 deletion tests/autotests/test_task02.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

# Fix import statements in try block to run tests
try:
from project.task2 import regex_to_dfa, graph_to_nfa
from project.to_finite_automaton_converters import regex_to_dfa, graph_to_nfa
except ImportError:
pytestmark = pytest.mark.skip("Task 2 is not ready to test!")

Expand Down