This commit is contained in:
2025-04-23 20:24:23 +03:00
parent 19159eb98d
commit 7030059bbb
8 changed files with 817 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
import random
class FiniteAutomaton:
def __init__(
self,
transitions: dict[str, list[tuple[str, str]]],
initial_state: str,
final_states: set[str],
alphabet: set[str],
):
self.transitions = transitions
self.initial_state = initial_state
self.final_states = final_states
self.alphabet = alphabet
def _get_next_state(self, current_state: str, char: str) -> str | None:
if current_state in self.transitions:
for transition, next_state in self.transitions[current_state]:
if char in transition:
return next_state
return None
def process_input(self, input_string: str) -> tuple[str, list[str]]:
current_state = self.initial_state
transitions_path = [current_state]
for char in input_string:
if char not in self.alphabet:
return f"Символ '{char}' не из алфавита", transitions_path
next_state = self._get_next_state(current_state, char)
if next_state is None:
return "Строка не соответствует", transitions_path
transitions_path.append(next_state)
current_state = next_state
return (
"Строка соответствует"
if current_state in self.final_states
else "Строка не соответствует"
), transitions_path
def generate_random_string(self, stop_probability: float = 0.3) -> str:
result = []
current_state = self.initial_state
while True:
if (
current_state in self.final_states
and random.random() < stop_probability
):
break
transition, next_state = random.choice(self.transitions[current_state])
char = random.choice(transition)
result.append(char)
current_state = next_state
return "".join(result)

82
lab2/programm/main.py Normal file
View File

@@ -0,0 +1,82 @@
from finite_automaton import FiniteAutomaton
def main():
alphabet = set("+-0123456789.,eE")
initial_state = "S0"
final_states = {"S2", "S4", "S7", "S8", "S9"}
transitions = {
"S0": [("+-", "S1"), ("123456789", "S2"), ("0", "S8")],
"S1": [("123456789", "S2"), ("0", "S8")],
"S2": [("0123456789", "S2"), (".,", "S3"), ("eE", "S5")],
"S3": [("0123456789", "S4")],
"S4": [("0123456789", "S4"), ("eE", "S5")],
"S5": [("+-", "S6"), ("123456789", "S7"), ("0", "S9")],
"S6": [("123456789", "S7"), ("0", "S9")],
"S7": [("0123456789", "S7")],
"S8": [(".,", "S3")],
}
automaton = FiniteAutomaton(
transitions=transitions,
initial_state=initial_state,
final_states=final_states,
alphabet=alphabet,
)
print("Конечный автомат для распознавания форматов вещественных чисел")
print("=" * 60)
print("Варианты команд:")
print(" - check <строка> - проверить, соответствует ли строка автомату")
print(
" - gen [<вероятность_остановки>] - сгенерировать случайную строку (по умолчанию 0.3)"
)
print(" - q - выход из программы")
print("=" * 60)
while True:
command = input("\nВведите команду: ").strip()
if not command:
continue
parts = command.split()
cmd = parts[0].lower()
if cmd == "q":
print("Выход из программы.")
break
elif cmd == "check":
input_string = ""
if len(parts) > 1:
input_string = " ".join(parts[1:]).strip()
message, transitions = automaton.process_input(input_string)
print(f"Результат: {message}")
print("Путь переходов:", " -> ".join(transitions))
elif cmd == "gen":
stop_prob = 0.3
if len(parts) > 1:
try:
stop_prob = float(parts[1])
if not (0 < stop_prob <= 1):
raise ValueError(
"Вероятность должна быть больше 0 и меньше либо равна 1"
)
except ValueError as e:
print(f"Ошибка: {e}")
continue
random_string = automaton.generate_random_string(stop_prob)
print(f"Сгенерированная строка: {random_string}")
else:
print(f"Неизвестная команда: {cmd}")
if __name__ == "__main__":
main()