Question

In: Computer Science

This is using Python, it is utilizing code from a Fraction class to create a Binary...

This is using Python, it is utilizing code from a Fraction class to create a Binary Class Please leave comments so I may be able to learn from this.

Instruction for Binary Class:

Exercise 6.18: Design an immutable class BinaryNumber, in the style of our Fraction
class. Internally, your only instance variable should be a text string that represents
the binary value, of the form '1110100'. Implement a constructor that takes a
string parameter that specifies the original binary value. Provide natural implemen-tations for the special methods __add__, __sub__, __lt__, __gt__, __eq__,__str__, and __int__. Note: with the exception of __int__, you are not to con-vert the internal values back to integers when implementing the operations; perform the arithmetic directly upon the internal binary representations.

Code from Fraction class:

from gcd import gcd

class Fraction:

def __init__(self, numerator=0, denominator=1):
if denominator == 0: # fraction is undefined
self._numer = 0
self._denom = 0
else:
factor = gcd( abs(numerator), abs(denominator) )
if denominator < 0: # want to divide through by negated factor
factor = -factor
self._numer = numerator // factor
self._denom = denominator // factor

######## Arithmetic Methods ########
def __add__(self, other):
return Fraction(self._numer * other._denom + other._numer * self._denom, self._denom * other._denom)

def __sub__(self, other):
return Fraction(self._numer * other._denom - other._numer * self._denom, self._denom * other._denom)

def __mul__(self, other):
return Fraction(self._numer * other._numer, self._denom * other._denom)

def __truediv__(self, other): # multiplication by reciprocal
return Fraction(self._numer*other._denom, self._denom*other._numer)

######## Comparison Methods ########
def __lt__(self, other):
return self._numer * other._denom < self._denom * other._numer
  

def __eq__(self, other):
if self._numer == other._numer and self._denom == other._denom:
return True
else:
return False

######## Type Conversion Methods ########
def __float__(self):
return float(self._numer) / self._denom

def __int__(self):
return int(float(self)) # convert to float, then truncate
  
def __str__(self):
if self._denom == 0:
return 'Undefined'
elif self._denom == 1:
return str(self._numer)
else:
return str(self._numer) + '/' + str(self._denom)

Solutions

Expert Solution

class BinaryNumber:
    def __init__(self, binary):
        self._bina = binary

    
    def normaliseString(str1,str2):
        diff = abs((len(str1) - len(str2)))
        if diff != 0:
            if len(str1) < len(str2):
                str1 = ('0' * diff) + str1
            
            else:
                str2 = ('0' * diff) + str2
           
        return [str1,str2]


    def __add__(self,other):
        x,y=self._bina,other._bina
        maxlen = max(len(x), len(x))
        
        #Normalize lengths
        x = x.zfill(maxlen)
        y = y.zfill(maxlen)

        result = ''
        carry = 0

        for i in range(maxlen-1, -1, -1):
            r = carry
            r += 1 if x[i] == '1' else 0
            r += 1 if y[i] == '1' else 0

            # r can be 0,1,2,3 (carry + x[i] + y[i])
            # and among these, for r==1 and r==3 you will have result bit = 1
            # for r==2 and r==3 you will have carry = 1

            result = ('1' if r % 2 == 1 else '0') + result
            carry = 0 if r < 2 else 1       

        if carry !=0 : result = '1' + result

        return BinaryNumber(result.zfill(maxlen))

    def __sub__(self,other):
        str1,str2=self._bina,other._bina
        if len(str1) == 0:
            return
        if len(str2) == 0:
            return 

        str1,str2 = normaliseString(str1,str2)
        startIdx = 0
        endIdx = len(str1) - 1
        carry = [0] * len(str1)
        result = ''
        
        while endIdx >= startIdx:
            x = int(str1[endIdx])
            y = int(str2[endIdx])
            if carry[endIdx]==-1 and x==0:
                sub=0
                carry[endIdx-1]=-1
            else:
                sub = (carry[endIdx] + x) - y
            
            if sub == -1:
                result += '1'
                carry[endIdx-1] = -1

            elif sub == 1:
                result += '1'
            elif sub == 0:
                result += '0'
            
            else:
                raise Exception('Error')

            endIdx -= 1
   
        return BinaryNumber(result[::-1])

    def __eq__(self,other):
        if self._bina^other._bina==0
            return True

    def __int__(self):
        binary = int(self._bina)
        decimal, i, n = 0, 0, 0
        while(binary != 0): 
            dec = binary % 10
            decimal = decimal + dec * pow(2, i) 
            binary = binary//10
            i += 1
        return decimal

    def __str__(self):
        return self._bina

    def __lt__(self,other):
        str1 = self._bina
        str2 = other._bina
        tot1,tot2,lent,power=0,0,len(str1)-1,0
        str1,str2 = normaliseString(str1,str2)
        for i in range(len(str1)):
            tot1+=int(str1[lent]) * pow(2,power)
            tot2+=int(str2[lent]) * pow(2,power)
            power+=1
            lent-=1

        if tot1>tot2:
            return False
        else:
            return True
            
    def __lt__(self,other):
        str1 = self._bina
        str2 = other._bina
        tot1,tot2,lent,power=0,0,len(str1)-1,0
        str1,str2 = normaliseString(str1,str2)
        for i in range(len(str1)):
            tot1+=int(str1[lent]) * pow(2,power)
            tot2+=int(str2[lent]) * pow(2,power)
            power+=1
            lent-=1

        if tot1>tot2:
            return True
        else:
            return False
            

    

Related Solutions

In python Using the example code from the HangMan program in our textbook, create a Word...
In python Using the example code from the HangMan program in our textbook, create a Word Guessing Game of your choice. Design a guessing game of your own creation. Choose a theme and build your words around that theme. Keep it simple. Note: I would highly recommend closely reviewing the HangMan code and program from Chapter 10 before starting work on this project. You can run the program via my REPL (Links to an external site.). Using python Similar to...
In Java, using the code provided for Class Candle, create a child class that meets the...
In Java, using the code provided for Class Candle, create a child class that meets the following requirements. Also compile and run and show output ------------------------------------------------------------------------ 1. The child class will be named  ScentedCandle 2. The data field for the ScentedCandle class is:    scent 3. It will also have getter and setter methods 4. You will override the parent's setHeight( ) method to set the price of a ScentedCandle object at $3 per inch (Hint:   price = height * PER_INCH) CODE...
Python Explain Code #Python program class TreeNode:
Python Explain Code   #Python program class TreeNode:    def __init__(self, key):        self.key = key        self.left = None        self.right = Nonedef findMaxDifference(root, diff=float('-inf')):    if root is None:        return float('inf'), diff    leftVal, diff = findMaxDifference(root.left, diff)    rightVal, diff = findMaxDifference(root.right, diff)    currentDiff = root.key - min(leftVal, rightVal)    diff = max(diff, currentDiff)     return min(min(leftVal, rightVal), root.key), diff root = TreeNode(6)root.left = TreeNode(3)root.right = TreeNode(8)root.right.left = TreeNode(2)root.right.right = TreeNode(4)root.right.left.left = TreeNode(1)root.right.left.right = TreeNode(7)print(findMaxDifference(root)[1])
Using Python code create a program only with beginners code. You are taking online reservations at...
Using Python code create a program only with beginners code. You are taking online reservations at the The inn Ask for your client’s name and save in a variable Ask how many nights your client will be staying and save in a variable Room rental is $145 per night Sales tax is 8.5% Habitation tax is $5 per night (not subject to sales tax) Print out: Client’s name Room rate per night Number of nights Room cost (room rate *...
Create a python code that calculates fixed point iteration method using a for loop.
Create a python code that calculates fixed point iteration method using a for loop.
PYTHON CODING Create a method (sortTraversal) for a Binary Search Tree that prints out the Binary...
PYTHON CODING Create a method (sortTraversal) for a Binary Search Tree that prints out the Binary Search Tree in ascending or deceasing order. The order type is an input to the method and can be "ascending" or "descending". The ascending input would return the node values of the tree beginning with the smallest and ending with the largest, descending returns the opposite. Discuss method's Big-O notation. Add proper and consistent documentation to identify code sections or lines to clearly identify...
Write code to create a Python dictionary called class. Add two entries to the dictionary: Associate...
Write code to create a Python dictionary called class. Add two entries to the dictionary: Associate the key 'class_name' with the value 'MAT123', and associate the key 'sect_num' with '211_145'
Code in C++. Using ONE of the following themes to create a class and demonstrate the...
Code in C++. Using ONE of the following themes to create a class and demonstrate the idea. Use this to create a solution (two ADTs and a driver program) to demonstrate the following concepts. Create a one page summary to describe where you are using each of these concepts. Themes:(PICK ONE) a house has a door a semester has a holiday break a cell phone has a shatterproof case a chair has a cushion Concepts to include: composition separating interface...
1. Create a flow chart from the algorithm then create python code. Algorithm: Tell the user...
1. Create a flow chart from the algorithm then create python code. Algorithm: Tell the user to enter their name, how many cars the user has, and the average number of cars per family in the users state. Create a variable to show the difference between the users number of cars and the average number of cars per family. Print the values of name, number of cars, average number of cars, and the difference in 2 decimal places.
C++ Build a binary tree using a binary tree class member function from the following array...
C++ Build a binary tree using a binary tree class member function from the following array of preorder traversal 3,9,20,15,7 and inorder traversal 9,3,15,20,7. Implement the constructor, destructor and all member functions including print postorder traversal of the binary tree.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT