在python中获得具有唯一数字的数字的最快方法是什么?

问题描述 投票:8回答:5

Lemme澄清:

获得两个数字之间所有唯一数字的每个数字的最快方法是什么。例如,10,000和100,000。

一些明显的值是12,345或23,456。我正在尝试寻找一种方法来收集所有这些对象。

for i in xrange(LOW, HIGH):
  str_i = str(i)
  ...?
python performance
5个回答
15
投票

使用itertools.permutations

itertools.permutations

我使用的事实是:

  • from itertools import permutations result = [ a * 10000 + b * 1000 + c * 100 + d * 10 + e for a, b, c, d, e in permutations(range(10), 5) if a != 0 ] 10000之间的数字有5或6位数字,但这里只有6位数字没有唯一数字,
  • [100000创建具有所有顺序的所有组合(因此itertools.permutations12345都将出现在结果中),具有给定的长度,
  • 您可以直接对整数序列进行排列(这样就无需转换类型的开销,],>
  • 编辑

感谢您接受我的回答,但这是其他人的数据,比较了提到的结果:

54321

所以,总结一下:

  • [>>> from timeit import timeit >>> stmt1 = ''' a = [] for i in xrange(10000, 100000): s = str(i) if len(set(s)) == len(s): a.append(s) ''' >>> stmt2 = ''' result = [ int(''.join(digits)) for digits in permutations('0123456789', 5) if digits[0] != '0' ] ''' >>> setup2 = 'from itertools import permutations' >>> stmt3 = ''' result = [ x for x in xrange(10000, 100000) if len(set(str(x))) == len(str(x)) ] ''' >>> stmt4 = ''' result = [ a * 10000 + b * 1000 + c * 100 + d * 10 + e for a, b, c, d, e in permutations(range(10), 5) if a != 0 ] ''' >>> setup4 = setup2 >>> timeit(stmt1, number=100) 7.955858945846558 >>> timeit(stmt2, setup2, number=100) 1.879319190979004 >>> timeit(stmt3, number=100) 8.599710941314697 >>> timeit(stmt4, setup4, number=100) 0.7493319511413574 取了solution no. 1
  • 解决方案号2(我原来的解决方案)取了7.96 s
  • [1.88 s取了solution no. 3
  • 解决方案号4(我更新的解决方案)为8.6 s
  • 最后的解决方案看起来比其他人提出的解决方案快10倍。

注意:我的解决方案中有一些我没有

测量的导入。我假设您的导入将发生一次,并且代码将被执行多次。如果不是这种情况,请根据您的需要调整测试。

EDIT#2

:我添加了另一种解决方案,因为甚至不需要对字符串进行操作-可以通过对实整数进行排列来实现。我敢打赌,这可以加快速度。

7
投票

便宜的方法:


4
投票

列表理解将在这里起作用(逻辑从nneonneo被盗):


1
投票

这里是从头开始的答案:


0
投票
def permute(L, max_len):
    allowed = L[:]
    results, seq = [], range(max_len)
    def helper(d):
        if d==0:
            results.append(''.join(seq))
        else:
            for i in xrange(len(L)):
                if allowed[i]:
                    allowed[i]=False
                    seq[d-1]=L[i]
                    helper(d-1)
                    allowed[i]=True
    helper(max_len)
    return results

A = permute(list("1234567890"), 5)
print A
print len(A)
print all(map(lambda a: len(set(a))==len(a), A))
© www.soinside.com 2019 - 2024. All rights reserved.