How to sort digits in a number?
>>> x = [4,5,81,5,28958,28] # first list
>>> print sorted(x)
[4, 5, 5, 28, 81, 28958]
>>> x
[4, 5, 81, 5, 28958, 28]
>>> x.sort() # sort the list in place
>>> x
[4, 5, 5, 28, 81, 28958]
>>> x.append(1) # add to the list
>>> x
[4, 5, 5, 28, 81, 28958, 1]
>>> sorted(x)
[1, 4, 5, 5, 28, 81, 28958]
As many others have pointed out, you can sort a number forwards like:
>>> int(''.join(sorted(str(2314))))
1234
That's pretty much the most standard way.
Reverse a number? Doesn't work well in a number with trailing zeros.
>>> y = int(''.join(sorted(str(2314))))
>>> y
1234
>>> int(str(y)[::-1])
4321
The [::-1]
notation indicates that the iterable is to be traversed in reverse order.
Sort the digits in ascending and descending orders:
ascending = "".join(sorted(str(number)))
descending = "".join(sorted(str(number), reverse=True))
Like this:
>>> number = 5896
>>> ascending = "".join(sorted(str(number)))
>>>
>>> descending = "".join(sorted(str(number), reverse=True))
>>> ascending
'5689'
>>> descending
'9865'
And if you need them to be numbers again (not just strings), call int()
on them:
>>> int(ascending)
5689
>>> int(descending)
9865
2020-01-30
>>> def kaprekar(number):
... diff = None
... while diff != 0:
... ascending = "".join(sorted(str(number)))
... descending = "".join(sorted(str(number), reverse=True))
... print(ascending, descending)
... next_number = int(descending) - int(ascending)
... diff = number - next_number
... number = next_number
...
>>> kaprekar(2777)
2777 7772
4599 9954
3555 5553
1899 9981
0288 8820
2358 8532
1467 7641
I don't know the python syntax, but thinking the generically, I would convert the input string into a character array, they do a sort on the character array, and lastly pipe it out.
As Mark Rushakoff already mentioned (but didn't solve) in his answer, str(n)
doesn't handle numeric n
with leading zeros, which you need for Kaprekar's operation. hughdbrown's answer similarly doesn't work with leading zeros.
One way to make sure you have a four-character string is to use the zfill
string method. For example:
>>> n = 2
>>> str(n)
'2'
>>> str(n).zfill(4)
'0002'
You should also be aware that in versions of Python prior to 3, a leading zero in a numeric literal indicated octal:
>>> str(0043)
'35'
>>> str(0378)
File "<stdin>", line 1
str(0378)
^
SyntaxError: invalid token
In Python 3, 0043
is not a valid numeric literal at all.