1
+ # A Simple Implementation of Push Down Automaton:
2
+ ## Defining the 6 tuples:
3
+ #> * Q-->finite set of sets
4
+ #> * Sigma-->finite set of input alphabet
5
+ #> * Gamma-->finite set of stack alphabet
6
+ #> * Delta-->transition relation
7
+ #> * Q0-->start state
8
+ #> * Z-->initial stack symbol
9
+ #> * F-->set of accepting states
10
+
11
+ # Defining the states:
12
+
13
+ #* state 0: starting state
14
+
15
+ #* state 1:From state 0 whenever it sees a 1 or 2, it moves to state 1+pushes the element onto the stack
16
+ #* state 1:From state 1 whenever it sees a 1 or 2, it remains in state 1+pushes the element onto the stack
17
+
18
+ #* state 2:From state 1 whenever it sees a 0, it moves to state 2+pops from the stack
19
+ #* state 2:From state 1 whenever it sees a 0, it remains in state 2+pops from the stack
20
+
21
+ #* state 3:From state 0, if it sees a 0,it moves to state 3,the rejected state
22
+ #* state 3:From state 2, if it sees a 1 or 2 , it moves to state 3, the rejected state
23
+ #* state 3:If at the end, the stack is not empty, it moves to state 3,the rejected state
24
+
25
+ #stack functions
26
+ def push (a ,list1 ):
27
+ #pushing to the stack/adding to the top of the stack
28
+ list1 .append (a )
29
+ return 1
30
+
31
+ def pop (list1 ):
32
+ #for poping from the stack/removing the top element of the stack
33
+ index = len (list1 )- 1
34
+ if (index > 0 ):
35
+ list1 .pop (index )
36
+ return 1
37
+ else :
38
+ return 0
39
+
40
+ # Q={0,1,2,3}
41
+ # Sigma={0,1,2}
42
+ # Starting state={0}
43
+ # Z=#
44
+ # F={2}
45
+
46
+ #setting the initial stack symbol
47
+ stack = ['#' ]
48
+ #setting the starting state
49
+ state = 0
50
+
51
+ #taking the input
52
+ input_string = input ('Enter the String:' )
53
+
54
+ #performing the operations
55
+ l = len (input_string )
56
+ i = 0
57
+ if l % 2 == 0 :
58
+ while i < l // 2 :
59
+ letter = int (input_string [i ])
60
+ if letter in [1 ,2 ]:
61
+ push (letter ,stack )
62
+ state = 1
63
+ else :
64
+ state = 3
65
+ break
66
+ i += 1
67
+
68
+ while i < l :
69
+ letter = int (input_string [i ])
70
+ if state == 3 :
71
+ break
72
+ if letter == 0 :
73
+ state = 2
74
+ pop (stack )
75
+ else :
76
+ state = 3
77
+ break
78
+ i += 1
79
+ else :
80
+ state = 3
81
+
82
+ if state == 2 and len (stack )!= 1 :
83
+ state = 3
84
+
85
+
86
+ #checking the final state and displaying the result
87
+ if (state == 2 ):
88
+ print ("The String is accepted" )
89
+ else :
90
+ print ("The String is rejected" )
0 commit comments