我知道有很多例子可以得到给定数的排列,但是如果不考虑前导的0,我就不知道如何实现它。
所以我的用例是这样的:
给定一个数字-比如240(输入范围是1000000),我希望看到输出没有24,42(数字有前导0)
下面是我使用python所做的
>>> digits = [int(x) for x in str(240)]
>>> n_digits = len(digits)
>>> n_power = n_digits - 1
>>> permutations = itertools.permutations(digits)
>>> values = [v * (10**(n_power - i)) for i, v in enumerate(itertools.repeat(1, n_digits))]
>>> positions = list(xrange(n_digits))
>>> [sum(item[x] * values[x] for x in positions) for item in permutations]
[240, 204, 420, 402, 24, 42]
>>>
知道吗?
最佳答案
查看不带24的输出,42(带前导0的数字)
>>> aRawLIST = [sum(item[x] * values[x] for x in positions) for item in permutations]
>>> [ aTruePOS for aTruePOS in aRawLIST if len( str( aTruePOS ) ) > 2 ]
[240, 204, 420, 402]
一般来说,may state
len( str( aTruePOS ) ) == len( str( anInputNUMBERasInteger ) )
经Danyc反对:
只有当输入的数字在范围(1000000)内时,您的解决方案才能工作。如果你尝试使用str('40')将不会显示任何内容–Danyc 9分钟前
>>> def aTest( anInputNUMBERasInteger ):
... digits = [ int( x ) for x in str( anInputNUMBERasInteger ) ]
... n_digits = len( digits )
... n_power = n_digits - 1
... permutations = itertools.permutations( digits )
... values = [ v * ( 10 ** ( n_power - i ) ) for i, v in enumerate( itertools.repeat( 1, n_digits ) ) ]
... positions = list( xrange( n_digits ) )
... raw = [ sum( item[x] * values[x] for x in positions ) for item in permutations ]
... return [ aTruePOS for aTruePOS in raw if len( str( aTruePOS ) ) == len( str( anInputNUMBERasInteger ) ) ]
...
>>> aTest( 240 )
[240, 204, 420, 402]
>>> aTest( 2400 )
[2400, 2400, 2040, 2004, 2040, 2004, 4200, 4200, 4020, 4002, 4020, 4002]
>>> aTest( 24 )
[24, 42]
>>> aTest( 40 )
[40]
>>> aTest( 5 )
[5]
>>> aTest( 1 )
[1]
Q.E.D.公司
关于python - 排除前导零的随机数的排列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26870643/