forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix_to_prefix_conversion.py
204 lines (176 loc) · 5.91 KB
/
infix_to_prefix_conversion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""
Output:
Enter an Infix Equation = a + b ^c
Symbol | Stack | Postfix
----------------------------
c | | c
^ | ^ | c
b | ^ | cb
+ | + | cb^
a | + | cb^a
| | cb^a+
a+b^c (Infix) -> +a^bc (Prefix)
"""
def infix_2_postfix(infix: str) -> str:
"""
>>> infix_2_postfix("a+b^c")
Symbol | Stack | Postfix
----------------------------
a | | a
+ | + | a
b | + | ab
^ | +^ | ab
c | +^ | abc
| + | abc^
| | abc^+
'abc^+'
>>> infix_2_postfix("1*((-a)*2+b)")
Symbol | Stack | Postfix
-------------------------------------------
1 | | 1
* | * | 1
( | *( | 1
( | *(( | 1
- | *((- | 1
a | *((- | 1a
) | *( | 1a-
* | *(* | 1a-
2 | *(* | 1a-2
+ | *(+ | 1a-2*
b | *(+ | 1a-2*b
) | * | 1a-2*b+
| | 1a-2*b+*
'1a-2*b+*'
>>> infix_2_postfix("")
Symbol | Stack | Postfix
----------------------------
''
>>> infix_2_postfix("(()")
Traceback (most recent call last):
...
ValueError: Invalid bracket position(s)
>>> infix_2_postfix("())")
Traceback (most recent call last):
...
ValueError: Invalid bracket position(s)
"""
stack = []
post_fix = []
priority = {
"^": 3,
"*": 2,
"/": 2,
"%": 2,
"+": 1,
"-": 1,
} # Priority of each operator
print_width = min(len(infix), 7)
# Print table header for output
print(
"Symbol".center(8),
"Stack".center(print_width),
"Postfix".rjust((print_width - 7) // 2 + 7),
sep=" | ",
)
print("-" * (print_width * 3 + 7))
for x in infix:
if x.isalpha() or x.isdigit():
post_fix.append(x) # if x is Alphabet / Digit, add it to Postfix
elif x == "(":
stack.append(x) # if x is "(" push to Stack
elif x == ")": # if x is ")" pop stack until "(" is encountered
if len(stack) == 0: # close bracket without open bracket
raise ValueError("Invalid bracket position(s)")
while stack[-1] != "(":
post_fix.append(stack.pop()) # Pop stack & add the content to Postfix
stack.pop()
else:
if len(stack) == 0:
stack.append(x) # If stack is empty, push x to stack
else: # while priority of x is not > priority of element in the stack
while (
len(stack) > 0
and stack[-1] != "("
and priority[x] <= priority[stack[-1]]
):
post_fix.append(stack.pop()) # pop stack & add to Postfix
stack.append(x) # push x to stack
if post_fix != []:
print(
x.center(8),
("".join(stack)).ljust(print_width),
"".join(post_fix),
sep=" | ",
) # Output in tabular format
else: # Post_fix is empty -> remove trailing space in table
print(
x.center(8) + " | " + ("".join(stack)).ljust(print_width) + " |"
) # Output in tabular format
while len(stack) > 0: # while stack is not empty
if stack[-1] == "(": # open bracket with no close bracket
raise ValueError("Invalid bracket position(s)")
post_fix.append(stack.pop()) # pop stack & add to Postfix
print(
" ".center(8),
("".join(stack)).ljust(print_width),
"".join(post_fix),
sep=" | ",
) # Output in tabular format
return "".join(post_fix) # return Postfix as str
def infix_2_prefix(infix: str) -> str:
"""
>>> infix_2_prefix("a+b^c")
Symbol | Stack | Postfix
----------------------------
c | | c
^ | ^ | c
b | ^ | cb
+ | + | cb^
a | + | cb^a
| | cb^a+
'+a^bc'
>>> infix_2_prefix("1*((-a)*2+b)")
Symbol | Stack | Postfix
-------------------------------------------
( | ( |
b | ( | b
+ | (+ | b
2 | (+ | b2
* | (+* | b2
( | (+*( | b2
a | (+*( | b2a
- | (+*(- | b2a
) | (+* | b2a-
) | | b2a-*+
* | * | b2a-*+
1 | * | b2a-*+1
| | b2a-*+1*
'*1+*-a2b'
>>> infix_2_prefix('')
Symbol | Stack | Postfix
----------------------------
''
>>> infix_2_prefix('(()')
Traceback (most recent call last):
...
ValueError: Invalid bracket position(s)
>>> infix_2_prefix('())')
Traceback (most recent call last):
...
ValueError: Invalid bracket position(s)
"""
new_infix = list(infix[::-1]) # reverse the infix equation
for i in range(len(new_infix)):
if new_infix[i] == "(":
new_infix[i] = ")" # change "(" to ")"
elif new_infix[i] == ")":
new_infix[i] = "(" # change ")" to "("
return (infix_2_postfix("".join(new_infix)))[
::-1
] # call infix_2_postfix on Infix, return reverse of Postfix
if __name__ == "__main__":
from doctest import testmod
testmod()
Infix = input("\nEnter an Infix Equation = ") # Input an Infix equation
Infix = "".join(Infix.split()) # Remove spaces from the input
print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")