vendredi 6 mai 2022

Kaprekar's constant (sorted(numbers)

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.




Aucun commentaire:

Enregistrer un commentaire