|
6 | 6 |
|
7 | 7 | class Algorithms(object):
|
8 | 8 |
|
9 |
| - @staticmethod |
10 |
| - def calculator(input, output): |
11 |
| - stack = StackAsLinkedList() |
| 9 | + def __init__(self): |
| 10 | + self.stack = StackAsLinkedList() |
| 11 | + |
| 12 | + def calculator(self, input, output): |
12 | 13 | for line in input.readlines():
|
13 | 14 | for word in line.split():
|
14 | 15 | if word == "+":
|
15 | 16 | print "it is +"
|
16 |
| - arg2 = stack.pop() |
17 |
| - arg1 = stack.pop() |
18 |
| - stack.push(arg1 + arg2) |
| 17 | + arg2 = self.stack.pop() |
| 18 | + arg1 = self.stack.pop() |
| 19 | + self.stack.push(arg1 + arg2) |
19 | 20 | elif word == "*":
|
20 | 21 | print "it is *"
|
21 |
| - arg2 = stack.pop() |
22 |
| - arg1 = stack.pop() |
23 |
| - stack.push(arg1 * arg2) |
| 22 | + arg2 = self.stack.pop() |
| 23 | + arg1 = self.stack.pop() |
| 24 | + self.stack.push(arg1 * arg2) |
24 | 25 | elif word == "-":
|
25 | 26 | print "it is -"
|
26 |
| - arg2 = stack.pop() |
27 |
| - arg1 = stack.pop() |
28 |
| - stack.push(arg1 - arg2) |
| 27 | + arg2 = self.stack.pop() |
| 28 | + arg1 = self.stack.pop() |
| 29 | + self.stack.push(arg1 - arg2) |
29 | 30 | elif word == "/":
|
30 | 31 | print "it is /"
|
31 |
| - arg2 = stack.pop() |
32 |
| - arg1 = stack.pop() |
33 |
| - stack.push(arg1 / arg2) |
| 32 | + arg2 = self.stack.pop() |
| 33 | + arg1 = self.stack.pop() |
| 34 | + self.stack.push(arg1 / arg2) |
34 | 35 | # exponential expression
|
35 | 36 | elif word == "^":
|
36 | 37 | print "it is ^"
|
37 |
| - arg2 = stack.pop() |
38 |
| - arg1 = stack.pop() |
39 |
| - stack.push(arg1 ** arg2) |
| 38 | + arg2 = self.stack.pop() |
| 39 | + arg1 = self.stack.pop() |
| 40 | + self.stack.push(arg1 ** arg2) |
40 | 41 | elif word == "=":
|
41 | 42 | print "it is ="
|
42 |
| - arg = stack.pop() |
| 43 | + arg = self.stack.pop() |
43 | 44 | output.write(str(arg) + "\n")
|
44 | 45 | print "ans is ", arg
|
45 | 46 | else:
|
46 | 47 | print "it is number"
|
47 | 48 | # make it double
|
48 |
| - stack.push(float(word)) |
| 49 | + self.stack.push(float(word)) |
| 50 | + |
| 51 | + # remove all by calling purge method of linked list |
| 52 | + def clear(self): |
| 53 | + self.stack.purge() |
49 | 54 |
|
| 55 | + # use the iterator of linked list to access every remaining element |
| 56 | + def printall(self): |
| 57 | + for ele in self.stack: |
| 58 | + print ele |
50 | 59 |
|
51 |
| -Algorithms.calculator(open("input.txt", 'r'), open("output.txt", 'w+')) |
| 60 | +a = Algorithms() |
| 61 | +a.calculator(open("input.txt", 'r'), open("output.txt", 'w+')) |
| 62 | +a.printall() |
| 63 | +a.clear() |
| 64 | +print "print all again" |
| 65 | +a.printall() |
0 commit comments