Reputation: 11
I'm having trouble understanding why issup("oFB","FooBar")
is returning False. How does iter(t)
behave during this loop?
refer to this https://leetcode.com/problems/camelcase-matching/ https://leetcode.com/problems/camelcase-matching/discuss/270029/JavaC%2B%2BPython-Check-Subsequence-and-Regax
I'm guessing iter(t)
starts at "FooBar"
, then goes to "ooBar"
the next iteration and so forth.
def issup(s, t):
it = iter(t)
return all(c in it for c in s)
Upvotes: 0
Views: 51
Reputation: 781096
iter(t)
returns an iterator that returns all the elements of t
. So it will return "F"
, "o"
, "o"
, "B"
, "a"
, and "r"
.
However, an iterator can only be used once; once it has returned all the elements, it will be empty. So the first time that the generator executes c in it
, it will step through the iterator until it finds a match for the value of c
. When it tries to look for the next c
, it will continue from where it left off the previous time. And if any of them doesn't find a match, it will reach the end of the iterator and none of the following c in it
tests will succeed.
So when you do issup("oFB", "FooBar")
, the first iteration finds the first o
. The second iteration looks for F
, but it can't be found because we're already past that element in the iterator. At this point, all()
returns False
.
Many Python errors are due to not realizing that iterators can only be stepped through once. E.g. something like this:
with open("filename") as f:
for _ in range(10):
for line in f:
# do stuff
f
is an iterator over the lines of the file. When you reach the end of the for line
loop, there's nothing left in it, so the next iteration of for _
will not have anything to loop over. In this case you can actually fix it with f.seek(0)
to rewind, but most iterators don't have something like this. The file
iterator is unusual in that it uses the state of the underlying stream, rather than keeping state of its own.
Upvotes: 2