Question

In: Computer Science

Write a program to convert a text-file containing expressions (one per line) into post-fix expressions outputted...

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

Solutions

Expert Solution

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:


Related Solutions

Write a program that reads a file called document.txt which is a text file containing an...
Write a program that reads a file called document.txt which is a text file containing an excerpt from a novel. Your program should print out every word in the file that contains a capital letter on a new line to the stdout. For example: assuming document.txt contains the text C++
You are given a text file containing a short text. Write a program that 1. Reads...
You are given a text file containing a short text. Write a program that 1. Reads a given text file : shortText.txt 2. Display the text as it is 3. Prints the number of lines 4. Prints the occurences of each letter that appears in the text. [uppercase and lowercase letter is treated the same]. 5. Prints the total number of special characters appear in the text. 6. Thedisplayofstep3,4and5aboveshouldbesaveinanoutputfile:occurencesText.txt write it in C++ programing Language
Write a Python program that reads a file, input by the user, containing one word/token per...
Write a Python program that reads a file, input by the user, containing one word/token per line with an empty line between sentences. The program prints out the longest word found in the file along with its length.
create a file with 1000 alphanumeric ones written one per line. Write a program in python...
create a file with 1000 alphanumeric ones written one per line. Write a program in python that randomly selects 100 of them, holds the index of each alphanumeric, adds the hash of the previous 100 and tries to find a random alphanumeric so that if it adds it to the list of indicators the SHA256 of the whole to have 10 zeros at the end. You start with the original Hash: 1111..111 my solution so far: import random import string...
Part I The input to the program will be a text file containing the information for...
Part I The input to the program will be a text file containing the information for a tolerance table. An example follows using the values from the first lecture on tolerance analysis. These values will be stored in a text file. The data is comma delimited, which means that each data field is separated by a comma. If the first word is ‘PART’ the following values are the nominal size, +/- impact, tolerance, and fixed/variable. If the first word is...
Write a C++ program to create a text file. Your file should contain the following text:...
Write a C++ program to create a text file. Your file should contain the following text: Batch files are text files created by programmer. The file is written in notepad. Creating a text file and writing to it by using fstream: to write to a file, you need to open thew file as write mode. To do so, include a header filr to your program. Create an object of type fsrteam. Open the file as write mode. Reading from a...
Write a program that takes in a line of text as input, and outputs that line...
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Quit", "quit", or "q" for the line of text. Ex: If the input is: Hello there Hey quit then the output is: ereht olleH yeH IN C++ PLEASE!
Write a C program that Reads a text file(any file)  and writes it to a binary file....
Write a C program that Reads a text file(any file)  and writes it to a binary file. Reads the binary file and converts it to a text file.
2. Write a program which reads in the text file generated in part one and writes...
2. Write a program which reads in the text file generated in part one and writes out the same data as a comma-separated values (CSV) file for further processing. The file should have a header line which identifies which column contains which values and should look something like this: Time, Potentiometer, Temperature, Light, Switch0, Switch1, Switch2, Switch3 That header line should be followed by detail lines containing the measurements and should look something like this (matching the above Arduino output):...
Write a program to check the mathematical expressions containing the following parentheses for validity:                 (         &n
Write a program to check the mathematical expressions containing the following parentheses for validity:                 (                 [                 { Hint: {(6 – 2) * 8} is a valid expression. [3 + (6 * 7) } is an invalid expression.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT