确定元组内是否存在连续序列

时间:2014-02-23 18:30:12

标签: python python-3.x

我希望确定元组中是否存在连续序列。

例如,我希望在这种情况下返回True

is_sequence_within((1,2), (1,2,3))
在这种情况下,

False

is_sequence_within((1,3), (1,2,3))

3 个答案:

答案 0 :(得分:2)

我觉得这是itertools会更优雅地处理的事情,但......

def is_sequence_within(seq, target):
    for i in range(len(target)-len(seq)+1):
        if seq == target[i:i+len(seq)]: return True
    return False

可替换地:

def is_sequence_within(seq, target):
    return any(seq==target[i:i+len(seq)] for i in range(len(target)+1-len(seq)))

答案 1 :(得分:2)

您可以尝试以下操作:

def is_subset(key, tup):
    for i in range(len(tup) - len(key) + 1):
        if key == tup[i : i + l]:
            return True
    return False

或以较短的方式:

def is_subset(key, tup):
    return any(key == tup[i:i + len(key)] for i in range(len(tup) - len(key) + 1))

<强>输出:

print is_subset((1, 2), (1, 2, 3)) # True
print is_subset((1, 3), (1, 2, 3)) # False

答案 2 :(得分:1)

一个简单的技巧是依赖子串搜索(在Python中进行了相当优化)

def is_sequence_within(needle, haystack):
    if len(needle) == 0:
        return True
    return ("," + ",".join(map(str, needle)) + "," in
            "," + ",".join(map(str, haystack)) + ",")

如果这是可行的和/或有效的,取决于元组的大小和内容是什么。

当然,如果你也搜索相同序列的许多子序列,那么缓存haystack字符串会好得多。