Python:找出整数列表是否一致

时间:2013-08-08 16:56:10

标签: python sequence itertools

我试图找出一个整数列表是一致的还是一段时间,这意味着两个相邻元素之间的差异必须恰好为1,并且数字必须单调递增。我found一个简洁的方法,我们可以按列表中的数字减去列表中元素的位置进行分组 - 当数字不连贯时,这种差异会发生变化。显然,当序列不包含间隙或重复时,应该只有一个组。

测试:

>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l2 = [1, 2, 3, 4, 5, 7]
>>> l3 = [1, 2, 3, 4, 5, 5]
>>> l4 = [1, 2, 3, 4, 5, 4]
>>> l5 = [6, 5, 4, 3, 2, 1]
>>> def is_coherent(seq):
...     return len(list(g for _, g in itertools.groupby(enumerate(seq), lambda (i,e): i-e))) == 1
... 
>>> is_coherent(l1)
True
>>> is_coherent(l2)
False
>>> is_coherent(l3)
False
>>> is_coherent(l4)
False
>>> is_coherent(l5)
False

它运作良好,但我个人认为,鉴于问题的简单性,这个解决方案有点过于复杂。你能想出一个更清晰的方法来实现同样的目标吗?

编辑:答案摘要

从下面给出的答案中,解决方案

def is_coherent(seq):
    return seq == range(seq[0], seq[-1]+1)
显然胜利。对于小列表(10 ^ 3个元素),它比groupby方法快10倍,并且(在我的机器上)仍然比下一个最佳方法快4倍(使用izip_longest) 。它具有最差的缩放行为,但即使对于具有10 ^ 8个元素的大型列表,它仍然比下一个最佳方法快两倍,这也是基于izip_longest的解决方案。

使用timeit获得的相关时间信息:

Testing is_coherent_groupby...
   small/large/larger/verylarge duration: 8.27 s, 20.23 s, 20.22 s, 20.76 s
   largest/smallest = 2.51
Testing is_coherent_npdiff...
   small/large/larger/verylarge duration: 7.05 s, 15.81 s, 16.16 s, 15.94 s
   largest/smallest = 2.26
Testing is_coherent_zip...
   small/large/larger/verylarge duration: 5.74 s, 20.54 s, 21.69 s, 24.62 s
   largest/smallest = 4.28
Testing is_coherent_izip_longest...
   small/large/larger/verylarge duration: 4.20 s, 10.81 s, 10.76 s, 10.81 s
   largest/smallest = 2.58
Testing is_coherent_all_xrange...
   small/large/larger/verylarge duration: 6.52 s, 17.06 s, 17.44 s, 17.30 s
   largest/smallest = 2.65
Testing is_coherent_range...
   small/large/larger/verylarge duration: 0.96 s, 4.14 s, 4.48 s, 4.48 s
   largest/smallest = 4.66

测试代码:

import itertools
import numpy as np
import timeit


setup = """
import numpy as np
def is_coherent_groupby(seq):
    return len(list(g for _, g in itertools.groupby(enumerate(seq), lambda (i,e): i-e))) == 1

def is_coherent_npdiff(x):
    return all(np.diff(x) == 1)

def is_coherent_zip(seq):
    return all(x==y+1 for x, y in zip(seq[1:], seq))

def is_coherent_izip_longest(l):
    return all(a==b for a, b in itertools.izip_longest(l, xrange(l[0], l[-1]+1)))

def is_coherent_all_xrange(l):
    return all(l[i] + 1 == l[i+1] for i in xrange(len(l)-1))

def is_coherent_range(seq):
    return seq == range(seq[0], seq[-1]+1)


small_list = range(10**3)
large_list = range(10**6)
larger_list = range(10**7)
very_large_list = range(10**8)
"""


fs = [
    'is_coherent_groupby',
    'is_coherent_npdiff',
    'is_coherent_zip',
    'is_coherent_izip_longest',
    'is_coherent_all_xrange',
    'is_coherent_range'
    ]


for n in fs:
    print "Testing %s..." % n
    t1 = timeit.timeit(
        '%s(small_list)' % n, 
        setup,
        number=40000
        )      
    t2 = timeit.timeit(
        '%s(large_list)' % n, 
        setup,
        number=100
        )     
    t3 = timeit.timeit(
        '%s(larger_list)' % n, 
        setup,
        number=10
        )
    t4 =  timeit.timeit(
        '%s(very_large_list)' % n, 
        setup,
        number=1
        )
    print "   small/large/larger/verylarge duration: %.2f s, %.2f s, %.2f s, %.2f s" % (t1, t2, t3, t4)
    print "   largest/smallest = %.2f" % (t4/t1)

试验机:

  • Linux 3.2.0(Ubuntu 12.04)
  • Python 2.7.3(gcc 4.1.2)
  • 使用英特尔编译器构建的numpy 1.6.2
  • CPU:E5-2650 @ 2.00GHz
  • 24 GB内存

6 个答案:

答案 0 :(得分:5)

怎么回合

sorted_list = sorted(my_list)
return sorted_list == range(sorted_list[0],sorted_list[-1]+1)

或者如果它已经排序则它只是连贯的

return my_list == range(my_list[0],my_list[-1]+1)

如果您使用的是python 3,则需要list(range(...))

答案 1 :(得分:2)

除非我在示例中忽略了某些内容,否则这个更简单的解决方案实际上更短。

>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l2 = [1, 2, 3, 4, 5, 7]
>>> l3 = [1, 2, 3, 4, 5, 5]
>>> l4 = [1, 2, 3, 4, 5, 4]
>>> l5 = [6, 5, 4, 3, 2, 1]
>>> 
>>> def is_coherent(seq):
...     return seq == range(seq[0], seq[0]+len(seq), 1)
... 
>>> is_coherent(l1)
True
>>> is_coherent(l2)
False
>>> is_coherent(l3)
False
>>> is_coherent(l4)
False
>>> is_coherent(l5)
False
>>> 

一些基本性能测试的结果似乎表明这种方法明显更快(我已将您的示例添加为is_coherent2):

Carl > python -m timeit -s 'from t import is_coherent, l1' 'is_coherent(l1)'
1000000 loops, best of 3: 0.782 usec per loop
Carl > python -m timeit -s 'from t import is_coherent, l3' 'is_coherent(l3)'
1000000 loops, best of 3: 0.796 usec per loop
Carl > python -m timeit -s 'from t import is_coherent2, l1' 'is_coherent2(l1)'
100000 loops, best of 3: 4.54 usec per loop
Carl > python -m timeit -s 'from t import is_coherent2, l3' 'is_coherent2(l3)'
100000 loops, best of 3: 4.93 usec per loop

答案 2 :(得分:2)

如果你正在寻找一个笨拙的解决方案:

import numpy as np

def is_coherent(x):
    return all(np.diff(x) == 1)

is_coherent(np.array([1,2,3,4,5]))
Out[39]: True

is_coherent(np.array([1,2,3,4,8]))
Out[40]: False

答案 3 :(得分:1)

def is_coherent(seq):
    return all(x==y+1 for x, y in zip(seq[1:], seq))

答案 4 :(得分:1)

这种短路并没有创建额外的列表,使其对测试非常大的列表很有用。

def is_coherent(l):
    return all(a==b for a, b in izip_longest(l, xrange(l[0], l[-1]+1)))

或者

def is_coherent(l):
    return all(l[i] + 1 == l[i+1] for i in xrange(len(l)-1))

答案 5 :(得分:0)

我不知道python,但我知道它的功能所以继承了一个小循环函数,如果你改变了正确python的语法,它将会这样做。

PSEUDO CODE

def is_coherent(seq):
     for x in xrange(1, len(seq)-1):
        if (seq[x+1]-seq[x] != 1)  return false;   
     return true