pythongeneratorstopiteration

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


Solution

  • 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))