'Kaprekar's constant (sorted(numbers) [duplicate]

Okay I've broken down step by step what the function needs to do. create random number, sort ascending and descending(needs both), subtract, sort the new number ascending and descending and repeat this until the number you get from subtraction is 6174 (preferably I'd like it to loop a time or two after as it should stay at 6174 "which is why it's called Kaprekar's constant".

What I currently have is a random number between 1000,9999. I kept getting (TypeError: 'int' object is not iterable) so I created a list and appended the random number to the list. I'm having issue with sorting the number ascending/descending.

import random
numbers = []
n = random.randint(1000,9999)
print(n)
numbers.append(n)
sorted(numbers)
print(numbers)

So I create a blank list, random number is generated and then printed, the number is then .append to the list and should sort and print the list.

The current output I get is 6988 [6988]

The expected output of what is written is 6988 [6889]

I attempted to use

print(numbers.sort(reverse=True))

this gave "None" I was expecting it to give [9886]

The only reason this is happening is that it wants to sort multiple items in the list opposed to sorting the numbers in the single item. I'm just not sure how to resolve it.



Solution 1:[1]

I'm not quite following you but I think you would like to have the individual digits of the randomly generated number as a list.

If so try doing:

my_str = str(n)
for my_char in my_str:
   numbers.append(int(my_char))

instead of:

numbers.append(n)

Solution 2:[2]

The first problem is a list.sort method returns None.

import random
numbers = []
n = random.randint(1000,9999)

numbers.append(n)

numbers.sort(reverse=True)
print(numbers)

Also reverse=True does not reverse the element but it reverses the list.

You can check this by this

import random
numbers = []
n = random.randint(1000,9999)


numbers.append(n)
numbers.append(10)

print(sorted(numbers))
print(sorted(numbers,reverse=True))

If you want to reverse element then use this one

import random
lst = []
num = random.randint(1000,9999)
print(num)
lst.append(num)

func = lambda e:int(str(e)[::-1]) # lambda function

lst = list(map(func,sorted(lst)))
print(lst)

NOTE:

  1. 1000 after reversing become 1 'cause int('0001') is 1.
  2. 4590 after reversing become 954 'cause int('0954') is 954.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gchapuis
Solution 2