HackerRank Day 19 Solution in Python: Interfaces

Today we will see the HackerRank Day 19 Solution in Python. The problem is named 2D Arrays, part of 30 Days of code on HackerRank. Let’s get started!

Day 19: Interfaces Problem statement

We are given the AdvancedArithmetic interface and the method declaration for the abstract divisorSum(n) method. We have to complete the implementation of the Calculator class, which implements the AdvancedArithmetic interface. Also, have to implement the divisorSum method must return the sum of all divisors of the input.

Sample Input


Sample Output

I implemented: AdvancedArithmetic

Explanation: The integer 6 is evenly divisible by 1, 2, 3, and 6. Our divisorSum method should return the sum of these numbers, which is 1+2+3+6=12. The Solution class then prints I implemented: AdvancedArithmetic on the first line, followed by the sum returned by divisorSum (which is 12) on the second line.

You can solve the problem here.

HackerRank Day 19 Solution in Python

#Create Interface AdvancedArithmetic
class AdvancedArithmetic(object):
    def divisorSum(n):
        raise NotImplementedError

#Create class Calculator
class Calculator(AdvancedArithmetic):
    #Method to calculate sum of divisors
    def divisorSum(self, n):
        total = 1
        for i in range(2, n+1):
            if n % i == 0:
                total += i
        return total

#Get input from user
n = int(input())

#Create object for Calculator classs
my_calculator = Calculator()

s = my_calculator.divisorSum(n)
print("I implemented: " + type(my_calculator).__bases__[0].__name__)

Code Explanation:

  • First, we create the Calculator class
  • Then, we create a method divisorSum, which is declared in the AdvancedArithmetic interface
  • In the divisorSum method, we calculate the sum of the divisors of the input given

Also Read:


Author: Ayush Purawr