I am looping over an itertools.permutation object and for efficiency, the loop breaks once the item is found. I understand that because I used the for loop I am unable to catch the StopIteration error when the generator is exhausted and the item is not found.
So far I have implemented a found flag, but it seems kinda hacky.
from itertools import permutations
def verify_string(name, compare):
name = name.lower().split()
compare = compare.lower().split()
p = permutations(compare, len(compare))
found = 0
for i in p:
if list(i) == name:
print(f'Found: {compare} in {name}')
found = 1
break
if not found:
print('Not Found')
name = 'guido van rossum'
compare = 'van guido rossum'
verify_string(name, compare)
>>Found: ['van', 'guido', 'rossum'] in ['guido', 'van', 'rossum']
I also thought of checking if not next(p, '') to see if it is exhausted but the item might be found in the generator's last item and will return True anyways.
From a Pythonic view, is there a way to manage looping over a generator that stops and return when an item is found and returns a different value only when the generator is exhausted.
nameas a tuple and test fori == name. This way, you can avoid creating a redundant copy of each permutation.