Created
November 1, 2016 04:29
-
-
Save jeresuikkila/8f17acf89682f9bb25562348631b3ffc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Solution to [2016-10-31] Challenge #290 [Easy] Kaprekar Numbers | |
# found at https://www.reddit.com/r/dailyprogrammer/comments/5aemnn/20161031_challenge_290_easy_kaprekar_numbers/ | |
def isKaprekar(number): | |
''' | |
Tests every number in range for being a Kaprekar number as defined at | |
https://en.wikipedia.org/wiki/Kaprekar_number | |
''' | |
squared = number ** 2 | |
str_squared = str(squared) | |
if len(str_squared) == 1 and number > 0: | |
return True if squared == number else False | |
for i in range(1, len(str_squared)): | |
first = int(str_squared[:i]) | |
second = int(str_squared[i:]) | |
if first == 0 or second == 0: | |
continue | |
if first + second == number: | |
return True | |
return False | |
def kaprekarsInRange(start, end): | |
''' | |
param start: integer | |
param end: integer, included in the range of tested numbers | |
Returns a list of kaprekars numbers in the range. | |
''' | |
kaprekars = [] | |
for num in range(start, end+1): | |
if isKaprekar(num): | |
kaprekars.append(num) | |
return kaprekars | |
# Test | |
print(kaprekarsInRange(0, 100000) == [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999, 17344, 22222, 38962, 77778, 82656, 95121, 99999]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment