给定数字的最小排列

fro*_*ost 3 python string algorithm permutation

我有一个数字作为字符串,我想找到由原始数字组成的最小数字,即

56340902138765401345 -> 10001233344455566789
Run Code Online (Sandbox Code Playgroud)

我正在将字符串转换为列表并对其进行排序。

num = '56340902138765401345'
a = list(num)
a.sort()
Run Code Online (Sandbox Code Playgroud)

由于数字不能以零开头(但我需要使用原始数字中的零),我正在寻找第一个非零元素并将其放在前面:

inext = next(i for i, x in enumerate(a) if x != '0')
a.insert(0, a.pop(inext))
Run Code Online (Sandbox Code Playgroud)

然后我将列表转换回字符串并显示它。

num2 = ''.join(map(str, a))
print(num2)
Run Code Online (Sandbox Code Playgroud)

它有效,但对我来说似乎不太蟒蛇或优雅。有没有更好的办法?

Jun*_*sor 5

我们可以数零。然后我们从数字中删除零,对它进行排序并重新组合。为了重新组装,我们使用第一个数字,然后添加回零,然后添加排序后的其余数字。

num = '56340902138765401345'

nzeros = num.count('0')
num = ''.join(sorted(num.replace('0', '')))
print num[0] + ('0' * nzeros) + num[1:]
Run Code Online (Sandbox Code Playgroud)

结果:

 10001233344455566789
Run Code Online (Sandbox Code Playgroud)