Modified Kaprekar Numbers

Problem statement-

Photo by Marten Bjork on Unsplash

Solution:-
An interesting hackerrank problem where we have to find the number of kaprekar numbers in a given range. Lets move towards the code, first we will declare a list “kap” which will all the kaprekar number.As we have to find the kaprekar number in a given range we will have to iterate each number in the range. After that we will square each number, then based on the length of the square value we will split the number.
For example:- n=9,sq_num=81.we will split 81 into 8 and 1.then we will add 8 and 1 which will give us 9 thus 9 is a Kaprekar number.

def kaprekarNumbers(p,q):
kap=[]
for num in range(p,q+1):
sq_n=[x for x in str(num**2)]
d=len(str(num))
if len(sq_n)==(2*d):
if (int(''.join(sq_n[:d]))+int(''.join(sq_n[d:])))==num:
kap.append(num)
elif len(sq_n)==1:
if int(''.join(sq_n[:d]))==num:
kap.append(num)
else:
if (int(''.join(sq_n[:d-1]))+int(''.join(sq_n[d-1:])))==num:
kap.append(num)
if len(kap)!=0:
print(*kap)
else:
print("INVALID RANGE")

After splitting we will add them and check if the add number is same as the number else we will move towards the next number.

Conclusion:-
There is no glory in practice but without practice there is no glory”.An excellent quote which sums up why practice is necessary in order to achieve goals.Keep moving and keep hustling….(cheers:-)

Work in progress