Question

In: Computer Science

python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value):...

python

class Node():

def __init__(self, value):
pass

class PostScript():

def __init__(self):
pass
  
def push(self, value):
pass
  
def pop(self):
return None
  
def peek(self):
pass
  
def is_empty(self):
pass

def stack(self):
pass
  
def exch(self):
pass
  
def index(self):
pass
  
def clear(self):
pass
  
def dup(self):
pass
  
def equal(self):
pass
  
def depth(self):
pass
  
stack = PostScript()

def decode(command_list):
for object in command_list:
if object == '=':
stack.equal()
elif object == 'count':
stack.depth()
elif object == 'clear':
stack.clear()
elif object == 'dup':
stack.dup()
elif object == 'exch':
stack.exch()
elif object == 'index':
stack.index()
elif object == 'pop':
stack.pop()
elif object == 'stack':
stack.stack()
else:
stack.push(object)

command = input()
command_list = command.split()
decode(command_list)
  

For this assignment you are to implement a PostScript command interpreter using a Stack. You must implement the stack using a singly-linked list. Solutions that use a data structure other than a singly-linked list will received no credit.

The interpreter must read and execute a string of PostScript commands based on the following definitions:
1. =
objn objn-1 … obj1 = : objn-1 … obj1
This command removes the topmost object form the stack and prints it.

  1. count
    objn … obj1count : [depth of the stack] objn … obj1
    This command puts the depth of the stack on the top of the stack.
  2. clear
    objn … obj1clear : [empty stack]
    This command removes all objects from the stack.
  3. dup
    objn … obj1 = : objn objn … obj1
    This command adds a duplicate copy of the top object to the stack .
  4. exch
    objn objn-1 … obj1 exch : objn-1 objn … obj1
    This command exchanges the position of the top two elements of the stack.
  5. index
    objn … obj1 a index : objn … obja … obj1
    This command adds a copy of the ath object to the top the stack.
  6. pop
    objn objn-1 … obj1 pop : objn-1 …. obj1
    This command removes the top element from the stack.
  7. stack
    This command prints a copy of the entire stack, starting from the top and working to the bottom..

    The input will be a series of data and commands separated by a space. The data will go onto the stack. Commands do not go onto the stack. You must write at least one separate method for each of the commands. You may reuse the standard Stack methods discussed in class: push(), pop(), peek() and is_empty(). A template file has been provided.

  

Solutions

Expert Solution

class Node:

              

               def __init__(self,value):

                              self.value = value

                              self.next = None

                             

class PostScript:

              

               def __init__(self):

                              self.top = None

                             

               def push(self,value):

                              node = Node(value)

                              if self.top == None:

                                             self.top = node

                              else:

                                             node.next = self.top

                                             self.top = node

              

               def pop(self):

                              if self.top != None:

                                             self.top = self.top.next

                                            

               def peek(self):

                              if self.top !=None:

                                             return self.top.value

                              else:

                                             return None

                                            

               def is_empty(self):

                              return(self.top == None)

                             

               def stack(self):

                             

                              if self.is_empty():

                                             print("Empty Stack")

                              else:      

                                             print("\n Stack:")

                                             node = self.top

                                             while(node != None):

                                                            print(node.value)

                                                            node = node.next

               def exch(self):

                              if(self.top != None and self.top.next != None):

                                             top1 = self.top

                                             self.top = self.top.next

                                             top2 = self.top

                                             self.top = self.top.next

                                             top1.next = self.top

                                             self.top = top1

                                             top2.next = self.top

                                             self.top = top2

              

               def index(self, a):  

                              curr = self.top

                              i=1

                              while(i < a and curr != None):

                                             curr = curr.next

                                             i = i + 1

                              if(i == a):

                                             node = Node(curr.value)

                                             node.next = self.top

                                             self.top = node  

              

               def clear(self):

                              self.top = None

                             

               def dup(self):

                              if(self.top != None):

                                             node = Node(self.top.value)

                                             node.next = self.top

                                             self.top = node

              

               def equal(self):

                              if self.top != None:

                                             node = self.top

                                             self.top = self.top.next

                                             print(node.value)

                              else:

                                             print('None')

                                            

               def depth(self):

                              if(self.is_empty()):

                                             self.push(0)

                              else:

                                             count = 0

                                             node = self.top

                                             while(node != None):

                                                            count = count + 1

                                                            node = node.next

                                             self.push(count)

                                            

                                            

stack = PostScript()

def decode(command_list):

               i=0

               while (i < len(command_list)):

                              #print(command_list[i])

                              if command_list[i] == '=':

                                             stack.equal()

                              elif command_list[i] == 'count':

                                             stack.depth()

                              elif command_list[i] == 'clear':

                                             stack.clear()

                              elif command_list[i] == 'dup':

                                             stack.dup()

                              elif command_list[i] == 'exch':

                                             stack.exch()

                              elif command_list[i] == 'index':

                                             i = i + 1

                                             print(command_list[i])

                                             stack.index(int(command_list[i]))

                              elif command_list[i] == 'pop':

                                             stack.pop()

                              elif command_list[i] == 'stack':

                                             stack.stack()

                              else:

                                             stack.push(command_list[i])

                              i = i + 1

command = raw_input()

command_list = command.split()

decode(command_list)                                

#end of program

Code Screenshot:


Related Solutions

For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)        &nb
For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)               style = color                return    def plane(self,oil)              liquid = self.oil + self.truck(color) For the plane method, I am getting an error that the class does not define __add__ inside init so I cannot use the + operator. How do I go about this.             
''' File: pyPatientLL.py Author: JD ''' class Node: #ADT        def __init__(self, p = None):             ...
''' File: pyPatientLL.py Author: JD ''' class Node: #ADT        def __init__(self, p = None):              self.name = ""              self.ss = self.age = int(0)              self.smoker = self.HBP = self.HFD = self.points = int(0)              self.link = None              #if list not empty              if p != None:                     p.link = self        ptrFront = ptrEnd = None choice = int(0) def menu():        print( "\n\tLL Health Clinic\n\n")        print( "1. New patient\n")        print( "2. View patient by...
using repl or python class House():    valuationRate = 10       def __init__(self,city,sqft,price):        ...
using repl or python class House():    valuationRate = 10       def __init__(self,city,sqft,price):         self.city = city         self.sqft = sqft         self.price = price           def getPrice(self):         return self.price    def applyValuation(self):         self.price += self.price * self.valuationRate/100 # create class Townhouse that inherits from class House # class Townhouse should have valuationRate = 5    # implement method setPrice(self,price) in class Townhouse    # create an object House: city=Atlanta, sqft=10000, price=200000   ...
How would I setup this dictionary for Python 3? class Student(object): def __init__(self, id, firstName, lastName,...
How would I setup this dictionary for Python 3? class Student(object): def __init__(self, id, firstName, lastName, courses = None): The “id”, “firstName” and “lastName” parameters are to be directly assigned to member variables (ie: self.id = id) The “courses” parameter is handled differently. If it is None, assign dict() to self.courses, otherwise assign courses directly to the member variable. Note: The “courses” dictionary contains key/value pairs where the key is a string that is the course number (like “course1”) and...
class Board: def __init__(self): self.pieces = [[None for i in range(8)] for j in range(8)] def...
class Board: def __init__(self): self.pieces = [[None for i in range(8)] for j in range(8)] def __str__(self): s = "" for j in range(7, -1, -1): #for each row for i in range(8): # for each column if self.pieces[j][i] is None: # if self.pieces[j][i] is None s += "." # populate the row with '.' val for each column else: s += self.pieces [j][i].get_symbol() s += "\n" #after each row add a new line return s # return after iterating...
In Python: def _nodeAtIndex(self, index): """Returns the reference to the node at the given index; If...
In Python: def _nodeAtIndex(self, index): """Returns the reference to the node at the given index; If index is out of range, raise IndexError """ # PROBLEM 2 # You can assume that index is non-negative. # You need to traverse the list and stop at the required index. # YOUR CODE HERE (THIS IS WHAT I HAVE CURRENTLY WRITTEN BUT I"M STUCK AND DON"T KNOW WHAT TO DO) while current != None: # use a while-loop. plist.append(current._element) # process the...
1) What is the argument in “class AddressBook(object):” 2) What is the roll of “def __init__(self):”?...
1) What is the argument in “class AddressBook(object):” 2) What is the roll of “def __init__(self):”? 3) What is the roll of “def __repr__ (self):”? 4) Please copy and run “Addressbook” Python program. Submit the code and the output 5) Discuss the two outputs’ differences (data type). 6) Please add 2 more people and report the output. Code: class AddressBook(object): def init_(self): self.people=[] def add_entry(self, new_entry): self.people.append(new_entry) class AddressEntry(object): def __init__(self, first_name=None, family_name= None, email_address= None, DOB= None): self.first_name =...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a,...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a, b):        self.a = a        self.b = b    def add(self):        return self.a + self.b    def mul(self):        return self.a * self.b    def div(self):        return self.a / self.b    def sub(self):        return self.a - self.b def playQuiz():    print("0. Exit")    print("1. Add")    print("2. Subtraction")    print("3. Multiplication")    print("4. Division")...
class Car: condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color...
class Car: condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg my_car = Car("Corvette", "Black", “30”) print my_car.model print my_car.color print my_car.MPG print my_car.condition Add class “getter” methods to return the values for model, color, and MPG Add class “setter” methods to change the existing values for model, color, and MPG. The value to be used in the methods will be passed as an input argument. Add class method that will calculate...
"""stack.py implements stack with a list""" class Stack(object): def __init__(self): #creates an empty stack. O(1) self.top...
"""stack.py implements stack with a list""" class Stack(object): def __init__(self): #creates an empty stack. O(1) self.top = -1 #the index of the top element of the stack. -1: empty stack self.data = [] def push(self, item): # add item to the top of the stack. O(1) self.top += 1 self.data.append(item) def pop(self): # removes and returns the item at the top O(1) self.top -=1 return self.data.pop() def peek(self): # returns the item at the top O(1) return self.data[len(self.data)-1] def isEmpty(self):...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT