|
| 1 | +from dataclasses import dataclass |
| 2 | +from typing import Self, Any, Iterable |
| 3 | +import json |
| 4 | +from abc import ABC, abstractmethod |
| 5 | +from itertools import count |
| 6 | + |
| 7 | +from ..common import PathOrStr |
| 8 | + |
| 9 | + |
| 10 | +class FiniteAutomaton(ABC): |
| 11 | + """Base class for finite automata""" |
| 12 | + @abstractmethod |
| 13 | + def accepts(self, s: str) -> bool: |
| 14 | + raise NotImplementedError |
| 15 | + |
| 16 | + @classmethod |
| 17 | + def from_file(cls, path: PathOrStr) -> Self: |
| 18 | + with open(path) as fp: |
| 19 | + data = json.load(fp) |
| 20 | + return cls.from_dict(data) |
| 21 | + |
| 22 | + @classmethod |
| 23 | + @abstractmethod |
| 24 | + def from_dict(cls, data: dict[str, Any]) -> Self: |
| 25 | + raise NotImplementedError |
| 26 | + |
| 27 | + def to_file(self, path: PathOrStr) -> None: |
| 28 | + data = self.to_dict() |
| 29 | + with open(path, "w") as fp: |
| 30 | + json.dump(data, fp, indent=4) |
| 31 | + |
| 32 | + @abstractmethod |
| 33 | + def to_dict(self) -> dict[str, Any]: |
| 34 | + raise NotImplementedError |
| 35 | + |
| 36 | + |
| 37 | +@dataclass |
| 38 | +class NFA(FiniteAutomaton): |
| 39 | + """ |
| 40 | + Non-deterministic finite automaton |
| 41 | +
|
| 42 | + Bonus I: support epsilon transitions (transition that "reads empty string") - DONE |
| 43 | + """ |
| 44 | + states: list[int] |
| 45 | + initial_state: int |
| 46 | + final_states: list[int] |
| 47 | + transitions: dict[int, dict[str, set[int]]] |
| 48 | + |
| 49 | + class Evaluator: |
| 50 | + def __init__(self, nfa: "NFA") -> None: |
| 51 | + self.nfa = nfa |
| 52 | + self.states: set[int] = self.nfa.epsilon_closure({nfa.initial_state}) |
| 53 | + |
| 54 | + def step(self, c: str) -> None: |
| 55 | + new_states = set() |
| 56 | + for u in self.states: |
| 57 | + new_states.update(self.nfa.transitions.get(u, {}).get(c, set())) |
| 58 | + |
| 59 | + self.states = self.nfa.epsilon_closure(new_states) |
| 60 | + |
| 61 | + def accepts(self, s: str) -> bool: |
| 62 | + evaluator = self.Evaluator(self) |
| 63 | + for c in s: |
| 64 | + evaluator.step(c) |
| 65 | + return len(evaluator.states.intersection(self.final_states)) > 0 |
| 66 | + |
| 67 | + @classmethod |
| 68 | + def from_dict(cls, data: dict[str, Any]) -> Self: |
| 69 | + transitions: dict[int, dict[str, set[int]]] = {} |
| 70 | + for u, c, v in data["transitions"]: |
| 71 | + transitions.setdefault(u, {}).setdefault(c, set()).add(v) |
| 72 | + |
| 73 | + return cls( |
| 74 | + states=data["states"], |
| 75 | + initial_state=data["initial_state"], |
| 76 | + final_states=data["final_states"], |
| 77 | + transitions=transitions, |
| 78 | + ) |
| 79 | + |
| 80 | + def to_dict(self) -> dict[str, Any]: |
| 81 | + transitions = [] |
| 82 | + for u, tmp in self.transitions.items(): |
| 83 | + for c, vs in tmp.items(): |
| 84 | + for v in vs: |
| 85 | + transitions.append([u, c, v]) |
| 86 | + |
| 87 | + return { |
| 88 | + "states": self.states, |
| 89 | + "initial_state": self.initial_state, |
| 90 | + "final_states": self.final_states, |
| 91 | + "transitions": transitions, |
| 92 | + } |
| 93 | + |
| 94 | + def copy(self) -> "NFA": |
| 95 | + return self.from_dict(self.to_dict()) |
| 96 | + |
| 97 | + def renumber_states(self, x0: int) -> "NFA": |
| 98 | + f = dict(zip(self.states, count(x0))) |
| 99 | + return NFA( |
| 100 | + states=[f[x] for x in self.states], |
| 101 | + initial_state=f[self.initial_state], |
| 102 | + final_states=[f[x] for x in self.final_states], |
| 103 | + transitions={ |
| 104 | + f[x]: {c: {f[y] for y in ys} for c, ys in d.items()} |
| 105 | + for x, d in self.transitions.items() |
| 106 | + }, |
| 107 | + ) |
| 108 | + |
| 109 | + def epsilon_closure(self, states: Iterable[int]) -> set[int]: |
| 110 | + closure = set(states) |
| 111 | + while True: |
| 112 | + new_closure = closure |
| 113 | + for u in closure: |
| 114 | + new_closure = new_closure | self.transitions.get(u, {}).get("", set()) |
| 115 | + if len(closure) == len(new_closure): |
| 116 | + break |
| 117 | + closure = new_closure |
| 118 | + return closure |
0 commit comments