How to sort numbers in a number?

I am trying to make a simple script in Python that takes a number and stores it in a variable, sorting the numbers in ascending and descending order and saving as in separate variables. Implementation constant Kaprekara .

This is probably a pretty Nubian question. But I'm new to this, and I couldn't find anything on Google that could help me. The site I found tried to explain how to use lists, but it didn’t work very well.

+5
source share
5 answers

Sort numbers in ascending and descending order:

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 again their number (and not just strings), call int()them:

>>> int(ascending)
5689
>>> int(descending)
9865
+12
>>> 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]

, , :

>>> int(''.join(sorted(str(2314))))
1234

.

? .

>>> y = int(''.join(sorted(str(2314))))
>>> y
1234
>>> int(str(y)[::-1])
4321

[::-1] , .

+3

( ) , str(n) n , . hughdbrown .

, , zfill. :

>>> n = 2
>>> str(n)
'2'
>>> str(n).zfill(4)
'0002'

, Python 3 :

>>> str(0043)
'35'
>>> str(0378)
  File "<stdin>", line 1
    str(0378)
           ^
SyntaxError: invalid token

Python 3 0043 .

+2

I do not know the python syntax, but, thinking in general, I would convert the input string to an array of characters, they sort in an array of characters and finally unload it.

+1
source

Here is the answer to the title question in Perl with a bias towards sorting 4-digit numbers for the Kaprekar algorithm. In this example, replace "shift" with the number to sort. It sorts the digits in a 4-digit number with a leading 0 ($ asc is sorted in ascending order, $ dec decreases) and displays a number with a leading 0:

my $num = sprintf("%04d", shift);
my $asc = sprintf("%04d", join('', sort {$a <=> $b} split('', $num)));
my $dec = sprintf("%04d", join('', sort {$b <=> $a} split('', $num)));
0
source

All Articles