fork download
  1. import matplotlib.pyplot as plt
  2. from matplotlib.patches import Rectangle
  3.  
  4. def draw_pda():
  5. fig, ax = plt.subplots(figsize=(10, 5))
  6.  
  7. # Draw states
  8. states = {
  9. 'q0': (0, 0),
  10. 'q1': (2, 0),
  11. 'q2': (4, 0),
  12. 'q3': (6, 0)
  13. }
  14. for state, pos in states.items():
  15. ax.add_patch(Rectangle(pos, 1, 1, fill=None))
  16. ax.text(pos[0] + 0.5, pos[1] + 0.5, state, ha='center', va='center')
  17.  
  18. # Draw transitions
  19. transitions = [
  20. ('q0', 'q0', 'a', 'A', 'A$'),
  21. ('q0', 'q0', 'a', 'A', 'AA'),
  22. ('q0', 'q1', 'b', 'A', 'B'),
  23. ('q1', 'q1', 'b', 'B', 'BB'),
  24. ('q1', 'q2', 'c', 'B', 'C'),
  25. ('q2', 'q2', 'c', 'C', 'CC'),
  26. ('q2', 'q3', '', 'C', 'C'),
  27. ('q2', 'q3', '', 'B', 'B'),
  28. ('q2', 'q3', '', 'A', 'A')
  29. ]
  30. for t in transitions:
  31. start = states[t[0]]
  32. end = states[t[1]]
  33. ax.annotate('', xy=(end[0] + 0.5, end[1] + 0.5), xytext=(start[0] + 0.5, start[1] + 0.5),
  34. arrowprops=dict(arrowstyle='->'))
  35. ax.text((start[0] + end[0]) / 2 + 0.25, (start[1] + end[1]) / 2 + 0.25, f'{t[2]}, {t[3]} → {t[4]}', fontsize=8)
  36.  
  37. ax.set_xlim(-1, 8)
  38. ax.set_ylim(-1, 2)
  39. ax.axis('off')
  40. plt.show()
  41.  
  42. draw_pda()
  43.  
Success #stdin #stdout 2.77s 56684KB
stdin
Standard input is empty
stdout
Standard output is empty