Skip to content

Commit b226362

Browse files
authored
Adjust table convention in output and doctests
1 parent ef52d63 commit b226362

File tree

1 file changed

+23
-14
lines changed

1 file changed

+23
-14
lines changed

Diff for: data_structures/stacks/infix_to_prefix_conversion.py

+23-14
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,12 @@ def infix_2_postfix(infix: str) -> str:
2727
"-": 1,
2828
} # Priority of each operator
2929

30-
print_width = len(infix)
31-
30+
print_width = len(infix) if len(infix) > 7 else 7
3231
# Print table header for output
3332
print(
3433
"Symbol".center(8),
3534
"Stack".center(print_width),
36-
"Postfix".center(print_width),
35+
"Postfix".rjust((print_width-7) // 2 + 7),
3736
sep=" | ",
3837
)
3938
print("-" * (print_width * 3 + 7))
@@ -61,14 +60,20 @@ def infix_2_postfix(infix: str) -> str:
6160
):
6261
post_fix.append(stack.pop()) # pop stack & add to Postfix
6362
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+
7277
while len(stack) > 0: # while stack is not empty
7378
if stack[-1] == "(": # open bracket with no close bracket
7479
raise ValueError("Invalid bracket position(s)")
@@ -77,16 +82,17 @@ def infix_2_postfix(infix: str) -> str:
7782
print(
7883
" ".center(8),
7984
("".join(stack)).ljust(print_width),
80-
("".join(post_fix)).ljust(print_width),
85+
"".join(post_fix),
8186
sep=" | ",
8287
) # Output in tabular format
88+
8389

8490
return "".join(post_fix) # return Postfix as str
8591

8692

8793
def infix_2_prefix(infix: str) -> str:
8894
"""
89-
>>> infix_2_prefix('a+b^c')
95+
>>> infix_2_prefix("a+b^c")
9096
Symbol | Stack | Postfix
9197
----------------------------
9298
c | | c
@@ -95,8 +101,9 @@ def infix_2_prefix(infix: str) -> str:
95101
+ | + | cb^
96102
a | + | cb^a
97103
| | cb^a+
104+
'+a^bc'
98105
99-
>>> infix_2_prefix('1*((-a)*2+b)')
106+
>>> infix_2_prefix("1*((-a)*2+b)")
100107
Symbol | Stack | Postfix
101108
-------------------------------------------
102109
( | ( |
@@ -112,10 +119,12 @@ def infix_2_prefix(infix: str) -> str:
112119
* | * | b2a-*+
113120
1 | * | b2a-*+1
114121
| | b2a-*+1*
122+
'*1+*-a2b'
115123
116124
>>> infix_2_prefix('')
117125
Symbol | Stack | Postfix
118126
----------------------------
127+
''
119128
120129
>>> infix_2_prefix('(()')
121130
Traceback (most recent call last):

0 commit comments

Comments
 (0)