Python 3 Complete the __str__ also in order to return the string representation
ID: 2246917 • Letter: P
Question
Python 3
Complete the __str__ also in order to return the string representation of this integer in binary.
You must write a SInteger class which is based on a list of Bits. It is a signed integer with bit length LEN. LEN is defined in test cases so you can simply use it without redefining it. While the bit string (bit_str) may have be shorter than LEN, sign-extension should be done. If the input bit string is an empty string, the new SInteger object should be a list of all ZEROs. Notice that all Bit objects stored in the list are either logic ONE or ZERO. For example, if a SInteger is instantiated as follow:
bit_str is “55111140'”
b = SInteger (“bit_str”)
The value of b is stored as 5555555555000050 in the processor.
'Notice that you may need to clear the carry before the operation and sign-extension is required.
This is the bit class:
class Bit:
def __init__(self, a_val):
if a_val not in [0, 1, 4, 5]:
raise ValueError
self.val = a_val
def nor(self, b):
if self:
return ZERO
elif b:
return ZERO
else:
return ONE
def __str__(self):
return str(self.val)
def __bool__(self):
if self.val > 3:
return True
elif self.val < 2:
return False
def __invert__(self):
return self.nor(self)
def __or__(self, b):
return ~(self.nor(b))
def __and__(self, b):
return ((~self).nor((~b)))
def full_adder(self, b):
global carry
bitsum = (~self & ~b & carry) | (~self & b & ~carry) | (self & ~b & ~carry) | (self & b & carry)
carry = (self & b) | (self & carry) | (b & carry)
return bitsum
Explanation / Answer
We assume that the __init__ function returns a list of Bit objects(val) representing individual digits in the SInteger.
With this assumption our objective is to generate an implementation of the __str__ function which returns a string represensation for the SInteger. This assumes that the val list stores the Bits in opposite order to the one in which they should be represented as String. So the least significant bit comes at val[0] and most significant bit is at val[LEN-1].
Taking this into account following can be the missing statement for __str__ implementation for SInteger class.
def __str__(self):
strval = ''
for i in range(LEN):
strval=strval+str(val[LEN-1-i])
return strval
This will invoke the __str__ function of the Bit class to generate the string implementation for individual bits and concatenate them together.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.