James Schinner
James Schinner

Reputation: 1579

Python StopIteration in generator comprehension

Python 3.6

Trying to write a function that returns the common string in a list of strings. Eg.

>>>find_common_string(*['test 1', 'test 2', 'test 3'])

would return

>>>'test '

I tried to prevent it from matching any other strings after the first False returned by equality(iterator) with a StopIteration in the generator expression

Can this be done? I get: #comparing a few long strings

TypeError: sequence item 130: expected str instance, type found

This is the code:

def equality(iterator):
    iterator = iter(iterator)
    try:
        first = next(iterator)
    except StopIteration:
        return True
    return all(first == rest for rest in iterator)

def find_common_string(*strings):
    result = zip(*strings)      
    result = (i[0] if equality(i) else StopIteration for i in result)
    return ''.join(result) #I tried to use this ^

References: check if all elements in a list are identical

Upvotes: 2

Views: 651

Answers (2)

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12845

StopIteration is a type

>>> print(type(StopIteration))
<class 'type'>

so if you return it this way - you only return type, but not a raised exception.

One of the ways - use itertools.takewhile - it stops on first non-matching element.

Upvotes: 1

cs95
cs95

Reputation: 402413

If you want to have your generator keep returning items until a condition is no longer met, you can use itertools.takewhile. Your problem will need a slight modification:

import itertools

def find_common_string(*strings): 
    result = itertools.takewhile(lambda x: equality(x), [i for i in zip(*strings)])
    return ''.join((i[0] for i in result)) 

Upvotes: 3

Related Questions