fork download
  1. def desc_digit(num):
  2. num_str = str(num)
  3. while not len(num_str) == 4:
  4. num_str = '0' + num_str
  5. num_list = list(num_str)
  6. output = ''
  7. while len(num_list) > 0:
  8. output += max(num_list)
  9. num_list.remove(max(num_list))
  10. return int(output)
  11.  
  12.  
  13. def largest_digit(num):
  14. num_str = str(num)
  15. return int(max(list(num_str)))
  16.  
  17.  
  18. def asc_digit(num):
  19. num_str = str(num)
  20. while not len(num_str) == 4:
  21. num_str += '0'
  22. num_list = list(num_str)
  23. output = ''
  24. while len(num_list) > 0:
  25. output += min(num_list)
  26. num_list.remove(min(num_list))
  27. return int(output)
  28.  
  29.  
  30. def kaprekar(num):
  31. assert len(str(num)) < 5, 'Please enter a number 4 digits or lower.'
  32. output = str(num) + ' -> '
  33. count = 0
  34. while not num == 6174:
  35. num = desc_digit(num) - asc_digit(num)
  36. count += 1
  37. return print(output + str(count))
  38.  
  39.  
  40. input = [6589, 5455, 6174]
  41. for i in input:
  42. kaprekar(i)
Success #stdin #stdout 0.01s 9992KB
stdin
Standard input is empty
stdout
6589 -> 2
5455 -> 5
6174 -> 0