0

I recently came across some python code I don't understand completely.

s = "abcdef"
x = "bde"
it = iter(s)
print all(c in it for c in x)

I understand that this code checks if x is a subsequence of s. Can someone explain or point me towards an article that explains what's exactly happening at c in it. What is calling the next method of iterator it?

0

1 Answer 1

1

It’s good to start with reading the documentation for the built-in function all():

Return True if all elements of the iterable are true (or if the iterable is empty).

That means that c in it for c in x is a “generator expression”: it produces values. The values it produces are of the boolean expression c in it (see the in operator) for all characters c in string x.

Here, the in operator is responsible for advancing the iterator. Note, however, that the True result is probably lucky. The iterator it can advance only once and because x = "bde" contains the letters in the same sequence as they appear in s = "abcdef", the whole expression works out to the expected result True. Reverse x = "edb" and the expression is False because the iterator is exhausted.

Sign up to request clarification or add additional context in comments.

5 Comments

"because all letters of x are also letters of s" - i.e x is a subset of s.
Judging by the question's use of the word "subsequence", it sounds like the code is supposed to return false for x = "edb" and s = "abcdef".
@user2357112, while the op’s commentary uses the term “subsequence” the code does not implement a subsequence, and "bde" is certainly not a subsequence (i.e. substring) of "abcdef".
@Jens: ...but it does, doesn't it? At least by the definition used in contexts like the longest increasing subsequence problem, where a subsequence doesn't have to be contiguous, as opposed to a substring, which does have to be contiguous.
@user2357112 in that case, I agree.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.