Skip to content

Instantly share code, notes, and snippets.

@TomColBee
Last active January 21, 2022 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TomColBee/4c4789a31720476285e8c5e2733af192 to your computer and use it in GitHub Desktop.
Save TomColBee/4c4789a31720476285e8c5e2733af192 to your computer and use it in GitHub Desktop.
Coderbyte Python Challenge: KaprekarsConstant
# Using the Python language, have the function KaprekarsConstant(num) take
# the num parameter being passed which will be a 4-digit number with at least
# two distinct digits.
# Your program should perform the following routine on the number:
# Arrange the digits in descending order and in ascending order
# subtract the smaller number from the bigger number. Then repeat the previous step.
# Performing this routine will always cause you to reach a fixed number: 6174.
# For example: if num is 3524 your program should return 3 because of the following steps:
# (1) 5432 - 2345 = 3087, (2) 8730 - 0378 = 8352, (3) 8532 - 2358 = 6174.
# Assumes number with 4 digits given
def KaprekarsConstant(num):
# Set var iterations to return later
iterations = 0
# Sort the numbers (asc by default)
sort_num = sorted(str(num))
# Join the list into a string
num_str = ''.join(sort_num)
# Loop until we find 6174
while num != 6174:
sort_num = sorted(str(num)) # Sort numbers
num_str = ''.join(sort_num) # Join to create a string
num_asc = int(num_str) # Create ascending number
num_desc = num_str[::-1] # Get descending number
# Create for loop to add 0's to decending number length = 4
for x in range(len(num_desc),4):
num_desc = num_desc + '0'
x += 1
num_desc = int(num_desc)
# Count iterations
iterations += 1
# Get new number
num = num_desc - num_asc
return iterations
print(KaprekarsConstant(input()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment