@@ -27,13 +27,12 @@ def infix_2_postfix(infix: str) -> str:
27
27
"-" : 1 ,
28
28
} # Priority of each operator
29
29
30
- print_width = len (infix )
31
-
30
+ print_width = len (infix ) if len (infix ) > 7 else 7
32
31
# Print table header for output
33
32
print (
34
33
"Symbol" .center (8 ),
35
34
"Stack" .center (print_width ),
36
- "Postfix" .center ( print_width ),
35
+ "Postfix" .rjust (( print_width - 7 ) // 2 + 7 ),
37
36
sep = " | " ,
38
37
)
39
38
print ("-" * (print_width * 3 + 7 ))
@@ -61,14 +60,20 @@ def infix_2_postfix(infix: str) -> str:
61
60
):
62
61
post_fix .append (stack .pop ()) # pop stack & add to Postfix
63
62
stack .append (x ) # push x to stack
64
-
65
- print (
66
- x .center (8 ),
67
- ("" .join (stack )).ljust (print_width ),
68
- ("" .join (post_fix )).ljust (print_width ),
69
- sep = " | " ,
70
- ) # Output in tabular format
71
-
63
+
64
+ if post_fix != []:
65
+ print (
66
+ x .center (8 ),
67
+ ("" .join (stack )).ljust (print_width ),
68
+ "" .join (post_fix ),
69
+ sep = " | " ,
70
+ ) #Output in tabular format
71
+
72
+ else : # Post_fix is empty -> remove trailing space in table
73
+ print (
74
+ x .center (8 ) + " | " + ("" .join (stack )).ljust (print_width ) + " |"
75
+ ) #Output in tabular format
76
+
72
77
while len (stack ) > 0 : # while stack is not empty
73
78
if stack [- 1 ] == "(" : # open bracket with no close bracket
74
79
raise ValueError ("Invalid bracket position(s)" )
@@ -77,16 +82,17 @@ def infix_2_postfix(infix: str) -> str:
77
82
print (
78
83
" " .center (8 ),
79
84
("" .join (stack )).ljust (print_width ),
80
- ( "" .join (post_fix )). ljust ( print_width ),
85
+ "" .join (post_fix ),
81
86
sep = " | " ,
82
87
) # Output in tabular format
88
+
83
89
84
90
return "" .join (post_fix ) # return Postfix as str
85
91
86
92
87
93
def infix_2_prefix (infix : str ) -> str :
88
94
"""
89
- >>> infix_2_prefix(' a+b^c' )
95
+ >>> infix_2_prefix(" a+b^c" )
90
96
Symbol | Stack | Postfix
91
97
----------------------------
92
98
c | | c
@@ -95,8 +101,9 @@ def infix_2_prefix(infix: str) -> str:
95
101
+ | + | cb^
96
102
a | + | cb^a
97
103
| | cb^a+
104
+ '+a^bc'
98
105
99
- >>> infix_2_prefix(' 1*((-a)*2+b)' )
106
+ >>> infix_2_prefix(" 1*((-a)*2+b)" )
100
107
Symbol | Stack | Postfix
101
108
-------------------------------------------
102
109
( | ( |
@@ -112,10 +119,12 @@ def infix_2_prefix(infix: str) -> str:
112
119
* | * | b2a-*+
113
120
1 | * | b2a-*+1
114
121
| | b2a-*+1*
122
+ '*1+*-a2b'
115
123
116
124
>>> infix_2_prefix('')
117
125
Symbol | Stack | Postfix
118
126
----------------------------
127
+ ''
119
128
120
129
>>> infix_2_prefix('(()')
121
130
Traceback (most recent call last):
0 commit comments