Skip to content

Commit fdca441

Browse files
authored
Add doctests, exceptions, type hints and fix bug for infix_to_prefix_conversion.py
Add doctests Add exceptions for expressions with invalid bracket positions Add type hints for functions Fix a bug on line 53 (57 in PR)
1 parent 895dffb commit fdca441

File tree

1 file changed

+60
-4
lines changed

1 file changed

+60
-4
lines changed

Diff for: data_structures/stacks/infix_to_prefix_conversion.py

+60-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
"""
1616

1717

18-
def infix_2_postfix(infix):
18+
def infix_2_postfix(infix: str) -> str:
1919
stack = []
2020
post_fix = []
2121
priority = {
@@ -26,6 +26,7 @@ def infix_2_postfix(infix):
2626
"+": 1,
2727
"-": 1,
2828
} # Priority of each operator
29+
2930
print_width = len(infix) if (len(infix) > 7) else 7
3031

3132
# Print table header for output
@@ -43,14 +44,18 @@ def infix_2_postfix(infix):
4344
elif x == "(":
4445
stack.append(x) # if x is "(" push to Stack
4546
elif x == ")": # if x is ")" pop stack until "(" is encountered
47+
if len(stack) == 0: # close bracket without open bracket
48+
raise ValueError("Invalid bracket position(s)")
49+
4650
while stack[-1] != "(":
4751
post_fix.append(stack.pop()) # Pop stack & add the content to Postfix
4852
stack.pop()
4953
else:
5054
if len(stack) == 0:
5155
stack.append(x) # If stack is empty, push x to stack
5256
else: # while priority of x is not > priority of element in the stack
53-
while len(stack) > 0 and priority[x] <= priority[stack[-1]]:
57+
while len(stack) > 0 and stack[-1] != '(' \
58+
and priority[x] <= priority[stack[-1]]:
5459
post_fix.append(stack.pop()) # pop stack & add to Postfix
5560
stack.append(x) # push x to stack
5661

@@ -62,6 +67,9 @@ def infix_2_postfix(infix):
6267
) # Output in tabular format
6368

6469
while len(stack) > 0: # while stack is not empty
70+
if stack[-1] == '(': # open bracket with no close bracket
71+
raise ValueError("Invalid bracket position(s)")
72+
6573
post_fix.append(stack.pop()) # pop stack & add to Postfix
6674
print(
6775
" ".center(8),
@@ -73,9 +81,54 @@ def infix_2_postfix(infix):
7381
return "".join(post_fix) # return Postfix as str
7482

7583

76-
def infix_2_prefix(infix):
77-
infix = list(infix[::-1]) # reverse the infix equation
84+
def infix_2_prefix(infix: str) -> str:
85+
"""
86+
>>> infix_2_prefix('a+b^c')
87+
Symbol | Stack | Postfix
88+
----------------------------
89+
c | | c
90+
^ | ^ | c
91+
b | ^ | cb
92+
+ | + | cb^
93+
a | + | cb^a
94+
| | cb^a+
95+
'+a^bc'
96+
97+
>>> infix_2_prefix('1*((-a)*2+b)')
98+
Symbol | Stack | Postfix
99+
-------------------------------------------
100+
( | ( |
101+
b | ( | b
102+
+ | (+ | b
103+
2 | (+ | b2
104+
* | (+* | b2
105+
( | (+*( | b2
106+
a | (+*( | b2a
107+
- | (+*(- | b2a
108+
) | (+* | b2a-
109+
) | | b2a-*+
110+
* | * | b2a-*+
111+
1 | * | b2a-*+1
112+
| | b2a-*+1*
113+
'*1+*-a2b'
114+
115+
>>> infix_2_prefix('')
116+
Symbol | Stack | Postfix
117+
----------------------------
118+
''
119+
120+
>>> infix_2_prefix('(()')
121+
Traceback (most recent call last):
122+
...
123+
ValueError: Invalid bracket position(s)
78124
125+
>>> infix_2_prefix('())')
126+
Traceback (most recent call last):
127+
...
128+
ValueError: Invalid bracket position(s)
129+
"""
130+
infix = list(infix[::-1]) # reverse the infix equation
131+
79132
for i in range(len(infix)):
80133
if infix[i] == "(":
81134
infix[i] = ")" # change "(" to ")"
@@ -88,6 +141,9 @@ def infix_2_prefix(infix):
88141

89142

90143
if __name__ == "__main__":
144+
from doctest import testmod
145+
testmod()
146+
91147
Infix = input("\nEnter an Infix Equation = ") # Input an Infix equation
92148
Infix = "".join(Infix.split()) # Remove spaces from the input
93149
print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")

0 commit comments

Comments
 (0)