Question

Pip does not have a remainder operation as in Python. One way to simulate y =...

Pip does not have a remainder operation as in Python. One way to simulate y = y % x with positive x and y is while y >= 0: y = y - x y = y + x After the loop, y < 0 for the first time. After the last line it is back to the proper range for the remainder: 0 <= y < x. Play computer to see that this works! Convert that code to Pip assembler file pipb.asm and test as in part A. The while loop condition translation is trickier here than in the earliest while translation example.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

DESCRIPTION:
One way to simulate y = y % x with positive x and y is while y >= 0: y = y - x y = y + x After the loop, y < 0 for the first time. After the last line it is back to the proper range for the remainder: 0< = y < x.

Solution:

The Solution for the problem can be obtained in the form of Binary Search Tree.Since, a way to simulate y=y%x with positive x and y is while y>=0:y=y-x y=y+x.After the loop,y<0 for the first time.This can be done by using the Binary Search Tree.

The Code is as follows:
class TreeNode:
    def __init__(self,key,val,left=None,right=None,parent=None):
        self.key = key
        self.payload = val
        self.leftChild = left
        self.rightChild = right
        self.parent = parent

    def hasLeftChild(self):
        return self.leftChild

    def hasRightChild(self):
       return self.rightChild

    def isLeftChild(self):
        return self.parent and self.parent.leftChild == self

    def isRightChild(self):
        return self.parent and self.parent.rightChild == self

    def isRoot(self):
        return not self.parent

    def isLeaf(self):
        return not (self.rightChild or self.leftChild)

    def hasAnyChildren(self):
        return self.rightChild or self.leftChild

    def hasBothChildren(self):
        return self.rightChild and self.leftChild

    def replaceNodeData(self,key,value,lc,rc):
        self.key = key
        self.payload = value
        self.leftChild = lc
        self.rightChild = rc
        if self.hasLeftChild():
            self.leftChild.parent = self
        if self.hasRightChild():
            self.rightChild.parent = self

class BinarySearchTree:

    def __init__(self):
        self.root = None
        self.size = 0

    def length(self):
        return self.size

    def __len__(self):
        return self.size

    def put(self,key,val):
        if self.root:
            self._put(key,val,self.root)
        else:
            self.root = TreeNode(key,val)
        self.size = self.size + 1

    def _put(self,key,val,currentNode):
        if key < currentNode.key:
            if currentNode.hasLeftChild():
                   self._put(key,val,currentNode.leftChild)
            else:
                   currentNode.leftChild = TreeNode(key,val,parent=currentNode)
        else:
            if currentNode.hasRightChild():
                   self._put(key,val,currentNode.rightChild)
            else:
                   currentNode.rightChild = TreeNode(key,val,parent=currentNode)

    def __setitem__(self,k,v):
       self.put(k,v)

    def get(self,key):
       if self.root:
           res = self._get(key,self.root)
           if res:
                  return res.payload
           else:
                  return None
       else:
           return None

    def _get(self,key,currentNode):
       if not currentNode:
           return None
       elif currentNode.key == key:
           return currentNode
       elif key < currentNode.key:
           return self._get(key,currentNode.leftChild)
       else:
           return self._get(key,currentNode.rightChild)

    def __getitem__(self,key):
       return self.get(key)

    def __contains__(self,key):
       if self._get(key,self.root):
           return True
       else:
           return False

    def delete(self,key):
      if self.size > 1:
         nodeToRemove = self._get(key,self.root)
         if nodeToRemove:
             self.remove(nodeToRemove)
             self.size = self.size-1
         else:
             raise KeyError('Error, key not in tree')
      elif self.size == 1 and self.root.key == key:
         self.root = None
         self.size = self.size - 1
      else:
         raise KeyError('Error, key not in tree')

    def __delitem__(self,key):
       self.delete(key)

    def spliceOut(self):
       if self.isLeaf():
           if self.isLeftChild():
                  self.parent.leftChild = None
           else:
                  self.parent.rightChild = None
       elif self.hasAnyChildren():
           if self.hasLeftChild():
                  if self.isLeftChild():
                     self.parent.leftChild = self.leftChild
                  else:
                     self.parent.rightChild = self.leftChild
                  self.leftChild.parent = self.parent
           else:
                  if self.isLeftChild():
                     self.parent.leftChild = self.rightChild
                  else:
                     self.parent.rightChild = self.rightChild
                  self.rightChild.parent = self.parent

    def findSuccessor(self):
      succ = None
      if self.hasRightChild():
          succ = self.rightChild.findMin()
      else:
          if self.parent:
                 if self.isLeftChild():
                     succ = self.parent
                 else:
                     self.parent.rightChild = None
                     succ = self.parent.findSuccessor()
                     self.parent.rightChild = self
      return succ

    def findMin(self):
      current = self
      while current.hasLeftChild():
          current = current.leftChild
      return current
    def remove(self,currentNode):
         if currentNode.isLeaf(): #leaf
           if currentNode == currentNode.parent.leftChild:
               currentNode.parent.leftChild = None
           else:
               currentNode.parent.rightChild = None
         elif currentNode.hasBothChildren(): #interior
           succ = currentNode.findSuccessor()
           succ.spliceOut()
           currentNode.key = succ.key
           currentNode.payload = succ.payload

         else: # this node has one child
           if currentNode.hasLeftChild():
             if currentNode.isLeftChild():
                 currentNode.leftChild.parent = currentNode.parent
                 currentNode.parent.leftChild = currentNode.leftChild
             elif currentNode.isRightChild():
                 currentNode.leftChild.parent = currentNode.parent
                 currentNode.parent.rightChild = currentNode.leftChild
             else:
                 currentNode.replaceNodeData(currentNode.leftChild.key,
                                    currentNode.leftChild.payload,
                                    currentNode.leftChild.leftChild,
                                    currentNode.leftChild.rightChild)
           else:
             if currentNode.isLeftChild():
                 currentNode.rightChild.parent = currentNode.parent
                 currentNode.parent.leftChild = currentNode.rightChild
             elif currentNode.isRightChild():
                 currentNode.rightChild.parent = currentNode.parent
                 currentNode.parent.rightChild = currentNode.rightChild
             else:
                 currentNode.replaceNodeData(currentNode.rightChild.key,
                                    currentNode.rightChild.payload,
                                    currentNode.rightChild.leftChild,
                                    currentNode.rightChild.rightChild)

mytree = BinarySearchTree()
mytree[3]="red"
mytree[4]="blue"
mytree[6]="yellow"
mytree[2]="at"

print(mytree[6])
print(mytree[2])


Add a comment
Know the answer?
Add Answer to:
Pip does not have a remainder operation as in Python. One way to simulate y =...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Using python 3.7.3 Challenge: Rock, Paper, Scissors GamePDF Description: Create a menu-driven rock, paper, scissors game...

    Using python 3.7.3 Challenge: Rock, Paper, Scissors GamePDF Description: Create a menu-driven rock, paper, scissors game in Python 3 that a user plays against the computer with the ability to save and load a game and its associated play statistics. Purpose: The purpose of this challenge is to assess the developer’s ability to create an interactive application with data persistence in Python 3. Requirements: Create a Rock, Paper, Scissors game in Python named rps.py according to the requirements specified in...

  • Piggy back on the programming project one you completed in module 3. You will use some...

    Piggy back on the programming project one you completed in module 3. You will use some of those concepts here again. We will be building this project inside out, start individual quiz and use a for loop to repeat it three times for three students. In this program you will be required to write a python program that generates math quizzes for students in second grade. Your program should do the following Ask the student for their name Provide 3...

  • You need not run Python programs on a computer in solving the following problems. Place your...

    You need not run Python programs on a computer in solving the following problems. Place your answers into separate "text" files using the names indicated on each problem. Please create your text files using the same text editor that you use for your .py files. Answer submitted in another file format such as .doc, .pages, .rtf, or.pdf will lose least one point per problem! [1] 3 points Use file math.txt What is the precise output from the following code? bar...

  • In this lab you will convert lab5.py to use object oriented programming techniques. The createList and...

    In this lab you will convert lab5.py to use object oriented programming techniques. The createList and checkList functions in lab5.py become methods of the MagicList class, and the main function of lab6.py calls methods of the MagicList class to let the user play the guessing game.                              A. (4pts) Use IDLE to create a lab6.py. Change the 2 comment lines at the top of lab6.py file: First line: your full name Second line: a short description of what the program...

  • Questin 1 (CO 2) Which of the following is not a valid name in python? last_name...

    Questin 1 (CO 2) Which of the following is not a valid name in python? last_name lastName last name lname Question 2 (CO 3) How many times will “Hello World” be displayed after the following code executes? num=2 while num<12:     print("Hello world")     num+=2 2 12 5 4 Question 3 (CO 1) The following code contains an error, what type of error is it and what line number is it? 1 count=1 2 while count<4 3    print("count = ",...

  • Enhance and correct a Tic Tac Toe game. The game is intended to be played against...

    Enhance and correct a Tic Tac Toe game. The game is intended to be played against a computer. The object TicTacToeBoard is initialized to indicate if the computer is the player 1 or player 2. Your task is to allow turns between the player and computer and to determine if a winner exists. Keyboard input implies using the Scanner object. Review Section 7.7 in the textbook. Ideally, do 1 task at a time and test the results. The tasks are...

  • For this project, each part will be in its oun matlab script. You will be uploading a total 3 m f...

    For this project, each part will be in its oun matlab script. You will be uploading a total 3 m files. Be sure to make your variable names descriptive, and add comments regularly to describe what your code is doing and hou your code aligns with the assignment 1 Iterative Methods: Conjugate Gradient In most software applications, row reduction is rarely used to solve a linear system Ar-b instead, an iterative algorithm like the one presented below is used. 1.1...

  • Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr,...

    Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr, int count, int key ) { 1: find the index of the first occurance of key. By first occurance we mean lowest index that contains this value. hint: copy the indexOf() method from Lab#3 into the bottom of this project file and call it from inside this remove method. The you will have the index of the value to remove from the array 2:...

  • You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people....

    You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people. One player is X and the other player is O. Players take turns placing their X or O. If a player gets three of his/her marks on the board in a row, column, or diagonal, he/she wins. When the board fills up with neither player winning, the game ends in a draw 1) Player 1 VS Player 2: Two players are playing the game...

  • I NEED HELP WITH DEBUGGING A C PROGRAM! PLEASE HEAR ME OUT AND READ THIS. I...

    I NEED HELP WITH DEBUGGING A C PROGRAM! PLEASE HEAR ME OUT AND READ THIS. I just have to explain a lot so you understand how the program should work. In C programming, write a simple program to take a text file as input and encrypt/decrypt it by reading the text bit by bit, and swap the bits if it is specified by the first line of the text file to do so (will explain below, and please let me...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT