Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a9e95a2

Browse files
Create InfixToPostfix
1 parent 2a17afa commit a9e95a2

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎InfixToPostfix

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
def is_operator(op):
2+
if op=='^' or op=='*' or op=='/' or op=='+' or op=='-':
3+
return True
4+
else:
5+
return False
6+
def preced(op, stack_op):
7+
precedence = {'+':1, '-':1, '*':2, '/':2, '^':3}
8+
try:
9+
if precedence[op]<=precedence[stack_op]:
10+
return True
11+
12+
except KeyError:
13+
return False
14+
def infix_to_postfix(exp):
15+
stack, res = [], ''
16+
for i in exp:
17+
# Case1: IsOperand()
18+
if i.isalpha():
19+
res += i
20+
# Case2: IsOpeningParenthesis()
21+
elif i=='(':
22+
stack.append(i)
23+
# Case3: IsClosingParenthesis()
24+
elif i==')':
25+
while len(stack)>0 and stack[-1]!='(':
26+
res += stack.pop()
27+
if len(stack)>0 and stack[-1]=='(':
28+
stack.pop()
29+
# Case4: IsOperator()
30+
elif is_operator(i):
31+
while len(stack)>0 and preced(i, stack[-1]):
32+
res += stack.pop()
33+
stack.append(i)
34+
while len(stack)>0:
35+
res += stack.pop()
36+
print(res)
37+
38+
for i in range(int(input())):
39+
infix = input()
40+
infix_to_postfix(infix)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /