简体   繁体   中英

How to sort digits in a number?

I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing Kaprekar's constant .

It's probably a pretty noobish question. But I'm new to this and I couldn't find anything on Google that could help me. A site I found tried to explain a way using lists, but it didn't work out very well.

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
>>> 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.

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.

我不知道 python 语法,但一般认为,我会将输入字符串转换为字符数组,他们对字符数组进行排序,最后将其输出。

Here's an answer to the title question in Perl, with a bias toward sorting 4-digit numbers for the Kaprekar algorithm. In the example, replace 'shift' with the number to sort. It sorts digits in a 4-digit number with leading 0's ($asc is sorted in ascending order, $dec is descending), and outputs a number with leading 0's:

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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM