[SOLVED] In Python, how to know whether a string contain a jump substring. like ‘abcd’ contain ‘ad’

Issue

This Content is from Stack Overflow. Question asked by tianlin zhang

In Python, how to know whether a string contain a jump substring. like ‘abcd’ contain ‘ad’
‘I very like play basketball’ contain ‘like basketball’



Solution

You can create an iterator from the test string and validate that every character in the subsequence can be found in the sequence of characters generated by the iterator:

def is_subsequence(a, b):
    seq = iter(b)
    return all(i in seq for i in a)

so that:

print(is_subsequence('ad', 'abcd'))
print(is_subsequence('adc', 'abcd'))

outputs:

True
False

Demo: https://ideone.com/jGdpis


This Question was asked in StackOverflow by tianlin zhang and Answered by blhsing It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?