MCPcopy Create free account
hub / github.com/geekcomputers/Python / Conversion

Class Conversion

Infix_to_Postfix.py:4–86  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2
3# Class to convert the expression
4class Conversion:
5 # Constructor to initialize the class variables
6 def __init__(self, capacity):
7 self.top = -1
8 self.capacity = capacity
9 # This array is used a stack
10 self.array = []
11 # Precedence setting
12 self.output = []
13 self.precedence = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
14
15 # check if the stack is empty
16 def isEmpty(self):
17 return True if self.top == -1 else False
18
19 # Return the value of the top of the stack
20 def peek(self):
21 return self.array[-1]
22
23 # Pop the element from the stack
24 def pop(self):
25 if not self.isEmpty():
26 self.top -= 1
27 return self.array.pop()
28 else:
29 return "$"
30
31 # Push the element to the stack
32 def push(self, op):
33 self.top += 1
34 self.array.append(op)
35
36 # A utility function to check is the given character
37 # is operand
38 def isOperand(self, ch):
39 return ch.isalpha()
40
41 # Check if the precedence of operator is strictly
42 # less than top of stack or not
43 def notGreater(self, i):
44 try:
45 a = self.precedence[i]
46 b = self.precedence[self.peek()]
47 return True if a <= b else False
48 except KeyError:
49 return False
50
51 # The main function that converts given infix expression
52 # to postfix expression
53 def infixToPostfix(self, exp):
54 # Iterate over the expression for conversion
55 for i in exp:
56 # If the character is an operand,
57 # add it to output
58 if self.isOperand(i):
59 self.output.append(i)
60
61 # If the character is an '(', push it to stack

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected