Question

In: Computer Science

Use python. DO NOT use pres existing libraries. Suppose there exists a text file called "expressions.txt"....

Use python. DO NOT use pres existing libraries. Suppose there exists a text file called "expressions.txt". This file contains simple arithmetic expressions written in infix notation. Using the Stack class, write code to implement the Shunting Yard Algorithm to generate postfix expressions. Each expression in expressions.txt is written on a single line. Moreover, each expression contains only numbers comprising a single digit. Each token is separated by whitespace. Write each postfix expression generated to a file "answers.txt". Only consider the operations +, -, /, *, and ^.

Solutions

Expert Solution

Code screenshots:

Code to copy:

class Stack:
   def __init__(self):
       self.arr = []
   def push(self, item):
       self.arr.append(item)
   def pop(self):
       self.arr.pop()
   def peek(self):
       return self.arr[len(self.arr)-1]
   def isEmpty(self):
       return len(self.arr)==0

def Shunting_Yard_Algorithm(expr):
   st = Stack()
   res = ''
   #split the expression into tokens with respect to white space
   token_list = expr.split()
   #precedence dictionary
   precedence = {'(':0, '+':1, '-':1, '*':2, '/':2, '^':3}
   for token in token_list:
        #If digit then add to result
       if token.isdigit():
           res +=token+' '
       #If operator
       elif token in '()+-*/^':
           #If stack is empty then just push the token
           if st.isEmpty():
               st.push(token)
           #If toke is ( then just push (
           elif token=='(':
               st.push(token)
           #If token is ) then pop elements until we reach ( and add to res
           elif token==')':
               while st.peek()!='(':
                   res += st.peek()+' '
                   st.pop()
               #pop ( from stack
               st.pop()
           else:
                #Pop and add to result until we found top of stack is lower prior than current token
               while token != '^' and not st.isEmpty() and precedence[st.peek()]>=precedence[token]:
                   res +=st.peek()+' '
                   st.pop()
               #Push the token
               st.push(token)
   #Pop and add to result until stack is empty
   while not st.isEmpty():
       res +=st.peek()+' '
       st.pop()
   #return the result
   return res


#Open the file in read mode
file = open('expressions.txt','r')
#split into line by line
lines = file.read().split('\n')
postfix=''
#pass each line to algorithms add result to postfix
for expr in lines:
   postfix += Shunting_Yard_Algorithm(expr)+'\n'
#close the file
file.close()

#Open file in write mode
file = open('answers.txt','w')
#Write the postfix to file
file.write(postfix)
#close the file
file.close()

expressions.txt

1 + 2 * ( 3 + 4 )
1 * 2 + ( 3 / 4 )
1 - 2 + 3 * ( 4 - 5 * 6 )
1 - 2 + 3
1 * 2 - 3 ^ 4 + 5 / 6
1 * 2 - 3 ^ 4 * 5 / 6
1 ^ 2 ^ 3
1 ^ 2 ^ 3 * 4 / 5 * 6 - 7 * ( 8 + 9 )
( 1 + 2 ) ^ ( 3 - 4 ) * ( 5 * 6 ) / ( 7 / 8 ) + ( 9 ^ 1 )

answers.txt

1 2 3 4 + * +
1 2 * 3 4 / +
1 2 - 3 4 5 6 * - * +
1 2 - 3 +
1 2 * 3 4 ^ - 5 6 / +
1 2 * 3 4 ^ 5 * 6 / -
1 2 3 ^ ^
1 2 3 ^ ^ 4 * 5 / 6 * 7 8 9 + * -
1 2 + 3 4 - ^ 5 6 * * 7 8 / / 9 1 ^ +


Related Solutions

how can we use cryptography libraries in Python
how can we use cryptography libraries in Python
Python: Word Frequencies (Concordance) 1. Use a text editor to create a text file (ex: myPaper.txt)...
Python: Word Frequencies (Concordance) 1. Use a text editor to create a text file (ex: myPaper.txt) It should contain at least 2 paragraphs with around 200 or more words. 2. Write a Python program (HW19.py) that asks the user to provide the name of the text file. Be SURE to check that it exists! Do NOT hard-code the name of the file! Use the entry provided by the user! read from the text file NOTE: (write your program so that...
Use Python to Complete the following on a single text file and submit your code and...
Use Python to Complete the following on a single text file and submit your code and your output as separate documents. For each problem create the necessary list objects and write code to perform the following examples: Sum all the items in a list. Multiply all the items in a list. Get the largest number from a list. Get the smallest number from a list. Remove duplicates from a list. Check a list is empty or not. Clone or copy...
In python 1.4. Write To a Text File Create a function that writes to a text...
In python 1.4. Write To a Text File Create a function that writes to a text file whatever data the user enters via keyboard. The user will first be asked to give the filename. Keep asking the user to enter data until they type Return without entering text. If the text file already exists then the data entered by the user is appended to the existing text file. The file you will write to will be named write_to_text_file.txt. Function name:...
This is a python file Reads information from a text file into a list of sublists....
This is a python file Reads information from a text file into a list of sublists. Be sure to ask the user to enter the file name and end the program if the file doesn’t exist. Text file format will be as shown, where each item is separated by a comma and a space: ID, firstName, lastName, birthDate, hireDate, salary Store the information into a list of sublists called empRoster. EmpRoster will be a list of sublists, where each sublist...
Using Python. A file exists on the disk named students.txt. The file contains several records, and...
Using Python. A file exists on the disk named students.txt. The file contains several records, and each record contains two fields: (1) the student’s name, and (2) the student’s score for the final exam. Write code that deletes the record containing “John Perz”as the student name. This the code i have so far but it's not working: import os def main(): found=False search='John Perz' student_file = open('student.txt','r') temp_file = open('temp_students.txt','w') name=student_file.readline() score='' while name !='': score=student_file.readline() name=name.rstrip('/n') score=score.rstrip('/n') if name...
Write a python program: There is a file called file 2. File2 is a txt file...
Write a python program: There is a file called file 2. File2 is a txt file and I have written the contents of file 2 below in the exact format it was in notepad. # This comment does not make sense # It is just to make it harder # The job description starts after this comment, notice that it has 4 lines. # This job description has 700150 hay system points\\ the incumbent will administer the spending of kindergarden...
Python programming problem! Suppose that there is a json file called data from the desktop. I...
Python programming problem! Suppose that there is a json file called data from the desktop. I want to print the value with the key of "year" and "country". Json file below: { "A":{ "year":11, "grade":A, "country":America}, "B":{ "year":18, "grade":C, "country":England}, "C":{ "year":19, "grade":B, "country":China},} I want a code that I can only replace the name of key from year to grade and the code could be work.
In Python: Assume a file containing a series of integers is named numbers.txt and exists on...
In Python: Assume a file containing a series of integers is named numbers.txt and exists on the computer's Disk. Write a program that reads al the numbers stored in the file and calculates their total. - create your own text file called numbers.txt and put in a set of 20 numbers (each number should be between 1 and 100). - Each number should be on its own line. - do not assume that the file will always have 20 numbers...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file must satisfy the following. Define a function named rinsert. This function will accept two arguments, the first a list of items to be sorted and the second an integer value in the range 0 to the length of the list, minus 1. This function shall insert the element corresponding to the second parameter into the presumably sorted list from position 0 to one less...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT