Created
June 18, 2024 18:08
-
-
Save Xnuvers007/b8c777865ab7f54f80b4bf6c419dba50 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
import networkx as nx | |
def draw_fsa(G, title): | |
pos = nx.spring_layout(G) | |
labels = nx.get_edge_attributes(G, 'label') | |
plt.figure(figsize=(12, 6)) | |
nx.draw(G, pos, with_labels=True, node_size=2000, node_color='skyblue', font_size=15, font_weight='bold') | |
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, font_size=12) | |
plt.title(title) | |
plt.show() | |
# Definisikan FSA M1 | |
M1 = nx.DiGraph() | |
M1.add_edges_from([ | |
('q0', 'q1', {'label': 'a'}), | |
('q1', 'q2', {'label': 'b'}) | |
]) | |
M1.nodes['q0']['initial'] = True | |
M1.nodes['q2']['accept'] = True | |
# Definisikan FSA M2 | |
M2 = nx.DiGraph() | |
M2.add_edges_from([ | |
('p0', 'p1', {'label': 'c'}), | |
('p1', 'p2', {'label': 'd'}) | |
]) | |
M2.nodes['p0']['initial'] = True | |
M2.nodes['p2']['accept'] = True | |
# Gabungan dari M1 dan M2 | |
Union = nx.DiGraph() | |
Union.add_edges_from([ | |
('start', 'q0', {'label': 'ε'}), | |
('start', 'p0', {'label': 'ε'}) | |
]) | |
Union = nx.compose(Union, M1) | |
Union = nx.compose(Union, M2) | |
# Konkatenasi dari M1 dan M2 | |
Concat = nx.DiGraph() | |
Concat = nx.compose(M1, M2) | |
Concat.add_edges_from([ | |
('q2', 'p0', {'label': 'ε'}) | |
]) | |
# Gambar automata | |
draw_fsa(M1, 'Automaton M1') | |
draw_fsa(M2, 'Automaton M2') | |
draw_fsa(Union, 'Union dari M1 dan M2') | |
draw_fsa(Concat, 'Concatenation dari M1 dan M2') |
Instagram: indradwi.25
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Penjelasan
Definisi FSA M1 dan M2:
M1 terdiri dari state q0, q1, q2 dengan transisi berdasarkan simbol a dan b.
M2 terdiri dari state p0, p1, p2 dengan transisi berdasarkan simbol c dan d.
Penggabungan M1 dan M2:
Membuat state awal baru yang disebut start.
Menambahkan transisi epsilon dari state start ke state awal M1 dan M2.
Konkatenasi M1 dan M2:
Menggabungkan semua state dan transisi dari M1 dan M2.
Menambahkan transisi epsilon dari state penerima M1 ke state awal M2.
Visualisasi:
Fungsi draw_fsa menggunakan pustaka networkx untuk membuat grafik automata dan matplotlib untuk menampilkannya, memperlihatkan state, transisi, dan labelnya.