Home > Uncategorized > Python ‘in’ operator with Iterator

Python ‘in’ operator with Iterator

I found use of in operator with iterator very useful. It would help write functional style code more easily.

list = [1,2,3,4]
list = iter(list)
assert 1 in list == True 

Explanation: iterator is matched until value 1 is matched, which is matched in the first place (index 0). list.next() would return 2 in this case.

list = [1,2,3,4]
list = iter(list)
assert 5 in list == False
list.next() # Throws exception

Explanation: 5 does not occur in the list. The list is all traversed to find occurence of 5. list.next() would raise StopIteration exception

Now lets see how to use ‘in’ operator with iterator to do something useful. Following function is written to check if the second argument is a subsequence of first argument.

def IS_word_subSequence_of_s(s,word):
 startIdx = 0
  for char in word:
    startIdx = s.find(char, startIdx)
    if startIdx == -1:
     return False
    else:
     startIdx += 1
 return True

Instead I found this code snippet [1] that very nicely use functional style to do the same thing.


def isSubsequence(s,x):
        it = iter(s)
        return all(c in it for c in x)

reference:
[1] https://discuss.leetcode.com/topic/80887/short-python-solutions

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: