Add numbers Aggregation: Rita’s next topic was aggregation. She wanted to take out the session in a similar way like she did in Composition topic. So to highlight the difference between Composition and Aggregation she gave the same problem to the students i.e. to add numbers but using aggregation topic.
But this time as problem constraint she asked the students to create 2 class Class A and Class B with 2 attributes each with the following attributes and methods.
attributes | Data type |
b | Integer |
c | integer |
Method name | Description |
addnums() | adds the numbers of class A |
attributes | data type |
d | integer |
e | integer |
Method name | Description |
addAllnums() | adds all the numbers of both class A and Class B |
Input format:
Input consists of the 4 integers values(>=0), numbers to be added.
Output format:
The output consists of the integer which indicates the sum of 4 values.
Print “Invalid Input” in case of negative integers.
Sample Input 1: 5 8 6 7 Sample Output 2: 26
Sample Input 2: -2 3 -7 8 2 Sample Output 2: Invalid Input
Solution
class A:
def __init__(self, a, b):
self.a = a
self.b = b
def addnums(self):
return self.a + self.b
class B:
def __init__(self, c, d):
self.c = c
self.d = d
def addnums(self):
return self.c + self.d
def addAllnums():
arr = {}
for i in range(4):
arr[i] = int(input())
if arr[0] < 0 or arr[1] < 0 or arr[2] < 0 or arr[3] < 0:
print("Invalid Input")
else:
a = A(arr[0], arr[1])
b = B(arr[2], arr[3])
print(a.addnums() + b.addnums())
addAllnums()
Happy Learning – If you require any further information, feel free to contact me.