In: Computer Science
Write a program to convert a text-file containing expressions (one per line) into post-fix expressions outputted to a file of your choice using a stack with one space between operators and variables (one letter variables) and/or constants (one digit constants). IN PYTHON please
SOURCE CODE: *Please follow the comments to better understand the code. **Please look at the Screenshot below and use this code to copy-paste. ***The code in the below screenshot is neatly indented for better understanding. class Conversion: # Constructor to initialize the class variables def __init__(self, capacity): self.top = -1 self.capacity = capacity # This stack is used a stack self.stack = [] # Precedence setting self.output = [] self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} # Pop the element from the stack def pop(self): if not self.is_empty(): self.top -= 1 return self.stack.pop() else: return "$" # Push the element to the stack def push(self, op): self.top += 1 self.stack.append(op) # Return the value of the top of the stack def peek(self): return self.stack[-1] # Check if the precedence of operator is # less than top of stack def not_greater(self, i): try: a = self.precedence[i] b = self.precedence[self.peek()] return True if a <= b else False except KeyError: return False # The main function that converts given infix expression # to postfix expression def infix_to_postfix(self, exp): # Iterate over the expression for conversion for i in exp: # If the character is an operand, # add it to output if self.is_operand(i): self.output.append(i) # If the character is an '(', push it to stack elif i == '(': self.push(i) # If the scanned character is an ')', pop and # output from the stack until and '(' is found elif i == ')': while (not self.is_empty()) and self.peek() != '(': a = self.pop() self.output.append(a) if not self.is_empty() and self.peek() != '(': return -1 else: self.pop() # OPERAND HERE else: while not self.is_empty() and self.not_greater(i): self.output.append(self.pop()) self.push(i) # pop all the operator from the stack while not self.is_empty(): self.output.append(self.pop()) # return as a string return " ".join(self.output) # check if the stack is empty def is_empty(self): return True if self.top == -1 else False def is_operand(self, ch): return ch.isalpha()
def main(): # READ THE FILE LINE BY LINE with open('test.txt') as file: for line in file.readlines(): # REPLACE THE SPACES FOR OUR CONVINIENCE line = line.replace(' ', '') # If the last character is \n. remove it if line[-1] == '\n': line = line[:-1] # Create an object obj = Conversion(len(line)) # call the method on the string post_fix = obj.infix_to_postfix(line) print(post_fix) if __name__ == '__main__': main()
=============
SCREENSHOT:
OUTPUT: