我知道有很多例子可以获得给定数字的排列,但我不知道如何在不考虑前导0的情况下实现它。
所以我的用例是这样的:
给出一个数字 - 比如240(输入范围是1,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]
>>>
有什么想法吗?
答案 0 :(得分:2)
你可以做到
>>> num = 240
>>> permutations = itertools.permutations(str(num))
>>> values = [int(''.join(c)) for c in permutations if (''.join(c))[0] != '0']
>>> values
>>> [240, 204, 420, 402]
编辑:
>>> values = [int(''.join(c)) for c in permutations]
>>> [c for c in values if c >= 10 ** (len(str(n)) - 1 ) ]
答案 1 :(得分:1)
最简单的方法是从列表中删除小于10 ^(k-1)的所有数字(其中k是输入的大小。
添加以下两行:
threshold = pow(10,n_digits-1)
[x for x in [sum(item[x] * values[x] for x in positions) for item in permutations] if x>=threshold]
答案 2 :(得分:-1)
>>> 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]
一般情况下,可以说明len( str( aTruePOS ) ) == len( str( anInputNUMBERasInteger ) )
根据DanyC的反对意见:
您的解决方案有效但仅当输入数字在范围内(10,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]