Skip to content

Commit a597b9f

Browse files
committed
solved(python): baekjoon 1918
1 parent 6235b0e commit a597b9f

File tree

4 files changed

+107
-0
lines changed

4 files changed

+107
-0
lines changed

baekjoon/python/1918/__init__.py

Whitespace-only changes.

baekjoon/python/1918/main.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import sys
2+
3+
read = lambda: sys.stdin.readline().rstrip()
4+
5+
6+
class Problem:
7+
def __init__(self):
8+
self.data = read()
9+
self.precedence = {"+": 1, "-": 1, "*": 2, "/": 2}
10+
11+
def solve(self) -> None:
12+
stack, output = [], ""
13+
14+
for word in self.data:
15+
if word.isalpha():
16+
output += word
17+
continue
18+
19+
if word == "(":
20+
stack.append(word)
21+
elif word == ")":
22+
while stack and stack[-1] != "(":
23+
output += stack.pop()
24+
stack.pop()
25+
else:
26+
while stack and stack[-1] != "(" and self.precedence[stack[-1]] >= self.precedence[word]:
27+
output += stack.pop()
28+
stack.append(word)
29+
30+
while stack:
31+
output += stack.pop()
32+
33+
print(output)
34+
35+
36+
if __name__ == "__main__":
37+
Problem().solve()

baekjoon/python/1918/sample.json

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
[
2+
{
3+
"input": [
4+
"A*(B+C)"
5+
],
6+
"expected": [
7+
"ABC+*"
8+
]
9+
},
10+
{
11+
"input": [
12+
"A+B"
13+
],
14+
"expected": [
15+
"AB+"
16+
]
17+
},
18+
{
19+
"input": [
20+
"A+B*C"
21+
],
22+
"expected": [
23+
"ABC*+"
24+
]
25+
},
26+
{
27+
"input": [
28+
"A+B*C-D/E"
29+
],
30+
"expected": [
31+
"ABC*+DE/-"
32+
]
33+
}
34+
]

baekjoon/python/1918/test_main.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import json
2+
import os.path
3+
import unittest
4+
from io import StringIO
5+
from unittest.mock import patch
6+
7+
from parameterized import parameterized
8+
9+
from main import Problem
10+
11+
12+
def load_sample(filename: str):
13+
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
14+
15+
with open(path, "r") as file:
16+
return [(case["input"], case["expected"]) for case in json.load(file)]
17+
18+
19+
class TestCase(unittest.TestCase):
20+
@parameterized.expand(load_sample("sample.json"))
21+
def test_case(self, case: str, expected: list[str]):
22+
# When
23+
with (
24+
patch("sys.stdin.readline", side_effect=case),
25+
patch("sys.stdout", new_callable=StringIO) as output,
26+
):
27+
Problem().solve()
28+
29+
result = output.getvalue().rstrip()
30+
31+
# Then
32+
self.assertEqual("\n".join(expected), result)
33+
34+
35+
if __name__ == "__main__":
36+
unittest.main()

0 commit comments

Comments
 (0)