2. Create a class Compute. Your task is to perform operator overloading. Following are the operators that would be overloaded. i. + The input for the operators would be same sized lists, same sized tuple or variable-sized dictionary. Following task needs to be completed: For + operator, if the caller is a list, then you need to add the contents of the two lists and return the same sized list. Similarly, you need to add the contents of the two tuples and return the same sized tuple. For a dictionary, you need to concatenate the two dictionaries. If the key is already present, then you need to merge the contents or values of those keys. Example: If input is list: [1,2,3,4] and [3.3,4,5,1.2], then for + operator output would be [4.4,6,8,5.2] Same applies for tuples. If input is dictionary: {1:’abc’,3:’xyz’,5:’test’} and {2:’test1’,3:’test2’,4:’test3’}, then for + operator output would be {1:’abc’,3:’xyztest2’,5:’test’, 2:’test1’,4:’test3’}
The above code has been implemented in Python 3 as per the details given above.
Appropriate comments have been added in the code for better understanding.
Below is the CODE, CODE SNIPPET (for indentation purposes) and OUTPUT.
CODE:
class Compute:
def __init__(self, x_comp, y_comp):
# Creating a constructor for class compute
self.x_comp = x_comp
self.y_comp = y_comp
def list_add(self):
# Adding the elements of two lists which are of same size
list_result = []
for i in range(0, len(self.x_comp)):
list_result.append(self.x_comp[i] + self.y_comp[i])
return list_result
def tuple_add(self):
# Adding the elements of two tuples which are of same size
tuple_result = [sum(x) for x in zip(self.x_comp,self.y_comp)]
return tuple_result
def dict_add(self):
# Adding the values of two dictionaries
for key in self.y_comp:
if key in self.x_comp:
self.x_comp[key] = self.y_comp[key] + self.x_comp[key]
else:
self.x_comp[key] = self.y_comp[key]
return self.x_comp
def main():
# Operator Overloading is done on input1 and input2
input1 = {1: 'abc', 3: 'xyz', 5: 'test'}
input2 = {2: 'test1', 3: 'test2', 4: 'test3'}
# Create object of the Compute class
obj1 = Compute(input1, input2)
# Check the type of input1 and input2 and call the appropriate method
if type(input1) == list and type(input2) == list:
result = obj1.list_add()
elif type(input1) == tuple and type(input2) == tuple:
result = obj1.tuple_add()
elif type(input1) == dict and type(input2) == dict:
result = obj1.dict_add()
else:
# If the input is not correct, exit the program.
print("Please enter the correct type")
exit()
print(result)
if __name__ == '__main__':
main()
CODE SNIPPET:
OUTPUT:
1) LIST
input1 = [1,2,3,4]
input2 = [3.3,4,5,1.2]
2) TUPLE
3) DICT
Get Answers For Free
Most questions answered within 1 hours.