Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding subsequence (nonconsecutive)

Tags:

python

string

If I have string needle and I want to check if it exists contiguously as a substring in haystack, I can use:

if needle in haystack:
    ...

What can I use in the case of a non-continuous subsequence? Example:

>>> haystack = "abcde12345"
>>> needle1 = "ace13"
>>> needle2 = "123abc"
>>> is_subsequence(needle1, haystack)
True
>>> is_subsequence(needle2, haystack)  # order is important!
False
like image 947
user4847061 Avatar asked Apr 29 '15 21:04

user4847061


Video Answer


2 Answers

I don't know if there's builtin function, but it is rather simple to do manually

def exists(a, b):
    """checks if b exists in a as a subsequence"""
    pos = 0
    for ch in a:
        if pos < len(b) and ch == b[pos]:
            pos += 1
    return pos == len(b)
>>> exists("moo", "mo")
True
>>> exists("moo", "oo")
True
>>> exists("moo", "ooo")
False
>>> exists("haystack", "hack")
True
>>> exists("haystack", "hach")
False
>>>
like image 177
Ishamael Avatar answered Oct 28 '22 06:10

Ishamael


Using an iterator trick:

it = iter(haystack)
all(x in it for x in needle)

This is only a concise version of the same idea presented in another answer.

like image 27
wim Avatar answered Oct 28 '22 05:10

wim