Skip to content

Commit a78737f

Browse files
committed
pro4 solved without parathesis
1 parent bf0de6d commit a78737f

File tree

3 files changed

+89
-5
lines changed

3 files changed

+89
-5
lines changed

unit3/infix_input.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
5 + 9 * 2 + 6 * 5 =
2+
5 * 8 + 6 / 10 =
3+
5 - 8 - 9 =
4+
5 * 8 * 9 =

unit3/output.txt

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
(((5.5 + 9) * 2) + (6 * 1.5)) =
2-
(5.5 + 5) =
3-
(((5.5 / 2) + 4) * 5) =
4-
(5 ^ 2) =
5-
(-5 + 5) =
1+
5 9 2 * + 6 5 * + =
2+
5 8 * 6 10 / + =
3+
5 8 - 9 - =
4+
5 8 * 9 * =

unit3/pro4.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from opus7.stackAsLinkedList import StackAsLinkedList
2+
3+
class Algorithms(object):
4+
5+
def __init__(self):
6+
self.stack = StackAsLinkedList()
7+
8+
def calculator(self, input, output):
9+
operators = ["+", "-"]
10+
priors = ["*", "/"]
11+
for line in input.readlines():
12+
flag = 0
13+
size = 0
14+
for word in line.split():
15+
'''
16+
match_left = re.search(r'\(', word)
17+
match_right = re.search(r'\)', word)
18+
if match_left:
19+
self.stack.push(word[1:])
20+
flag = 1
21+
if match_right:
22+
self.stack.push(word[:-1])
23+
'''
24+
if word in operators:
25+
print "it is an operator: ", word
26+
while size >= 3:
27+
arg2 = self.stack.pop()
28+
op = self.stack.pop()
29+
arg1 = self.stack.pop()
30+
size -= 3
31+
self.stack.push("%s %s %s" % (arg1, arg2, op))
32+
size += 1
33+
print "push ", arg1, arg2, op
34+
self.stack.push(word)
35+
print "pushing ", word
36+
size += 1
37+
flag = 0
38+
elif word in priors:
39+
print "it is a prior: ", word
40+
# indicating there are a pair of arg1 * arg2 in stack
41+
# waiting for poping out
42+
if flag == 1 and size >= 3:
43+
arg2 = self.stack.pop()
44+
op = self.stack.pop()
45+
arg1 = self.stack.pop()
46+
size -= 3
47+
self.stack.push("%s %s %s" % (arg1, arg2, op))
48+
size += 1
49+
print "push ", arg1, arg2, op
50+
# push the operator itself
51+
self.stack.push(word)
52+
print "pushing ", word
53+
size += 1
54+
flag = 1
55+
elif word == "=":
56+
print "it is ="
57+
while size >= 3:
58+
arg2 = self.stack.pop()
59+
op = self.stack.pop()
60+
arg1 = self.stack.pop()
61+
size -= 3
62+
self.stack.push("%s %s %s" % (arg1, arg2, op))
63+
size += 1
64+
print "push ", arg1, arg2, op
65+
output.write("%s %s %s = \n" % (arg1, arg2, op))
66+
print "writing into files", arg1, arg2, op
67+
else:
68+
print "it is number: ", word
69+
self.stack.push(word)
70+
print "pushing ", word
71+
size += 1
72+
73+
74+
75+
76+
77+
78+
a = Algorithms()
79+
a.calculator(open("infix_input.txt", 'r'), open("output.txt", 'w+'))
80+
81+

0 commit comments

Comments
 (0)