Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 检查元组中至少有5个连续数字_Python 3.x_Tuples - Fatal编程技术网

Python 3.x 检查元组中至少有5个连续数字

Python 3.x 检查元组中至少有5个连续数字,python-3.x,tuples,Python 3.x,Tuples,我有一个元组a,我想检查它是否包含至少5个连续的数字。最节省时间的方法是什么 A=(1,4,5,6,7,8,12)-->正确 这在蒙特卡罗模拟中用于检查一张7张牌的扑克牌是否包含一条直线。假设一个由7个不同整数组成的排序元组。如果串联有5个整数,即(n,n+1,n+2,n+3,n+4),则它们必须分别从位置0、1或2开始,并在位置4、5或6结束 straight = any(a[4+i] - a[i] == 4 for i in (0,1,2)) 更新:如果序列长度不固定: (由tobias_

我有一个元组a,我想检查它是否包含至少5个连续的数字。最节省时间的方法是什么

A=(1,4,5,6,7,8,12)-->正确


这在蒙特卡罗模拟中用于检查一张7张牌的扑克牌是否包含一条直线。

假设一个由7个不同整数组成的排序元组。如果串联有5个整数,即(n,n+1,n+2,n+3,n+4),则它们必须分别从位置0、1或2开始,并在位置4、5或6结束

straight = any(a[4+i] - a[i] == 4 for i in (0,1,2))
更新:如果序列长度不固定: (由tobias_k在评论中提出)


我不认为有一个简单的单行程序可以实现这一点,但基本上你只需要循环列表中的元素,检查它是否比上一个多一个,如果运行计数达到5,则返回True。你还必须考虑有两张相同值的卡。

def has_straight(values, req=5):
    last = count = None
    for x in values:
        if x - 1 == last:
            count += 1  # one more on the straight
        elif x == last:
            pass        # same value as before
        else:
            count = 1   # start a new straight
        if count >= req:
            return True
        last = x
    return False
一些例子:

has_straight((1, 4, 5, 6, 7, 10, 12))  # no straight -> False
has_straight((1, 4, 5, 6, 7, 8, 12))   # straight in middle -> True
has_straight((1, 2, 3, 4, 5, 10, 12))  # at beginning -> True
has_straight((1, 2, 8, 9, 10, 11, 12)) # at very end -> True
has_straight((1, 2, 2, 3, 4, 4, 5))    # straight with dupes -> True

复杂性将是O(n),这是它可能得到的最好结果,因为您必须检查每个数字。

请显示您尝试过的代码,以便元组包含5到7个数字。如何相应地调整(0,1,2)?这只适用于没有重复数字的情况,但在扑克牌中,可能存在重复值,例如
[1,1,1,2,2,5,5]
将使用您的算法生成
True
。是的,但在我的算法中,重复的数字会被过滤掉,因此有时只有5位数字。我可以用另一个循环替换(0,1,2)吗?对于范围内的j(len(A)-4)))不起作用,但它一定是类似的吗?@Nicolas,如果你过滤掉了任何重复,那么这应该会起作用。您可以将
(0,1,2)
替换为工作正常的
范围(len(a)-4)
,唯一的问题是,我如何才能找出顺序中最高的数字?由于我使用了“any”,这些信息正在丢失。有没有关于如何获得连续顺序中最高数字的索引的建议?
has_straight((1, 4, 5, 6, 7, 10, 12))  # no straight -> False
has_straight((1, 4, 5, 6, 7, 8, 12))   # straight in middle -> True
has_straight((1, 2, 3, 4, 5, 10, 12))  # at beginning -> True
has_straight((1, 2, 8, 9, 10, 11, 12)) # at very end -> True
has_straight((1, 2, 2, 3, 4, 4, 5))    # straight with dupes -> True