correct syntax to use the 'any' function with a list compression or generator

58 views Asked by At

Trying to figure out how to turn this below function into one that use any. So that it doesn't have to build the whole list and then check the list. Also is there a more efficient to handle this problem then how I am.(Finding all permutations, than matching.

import itertools
def is_merge(s, part1, part2):
    for x in [''.join(word) for word in (itertools.permutations(part1+part2))]:
        if x == s:
            return True
     return False
1

There are 1 answers

0
jmd_dk On BEST ANSWER

I'm not sure about the most efficient way to do this, but using any will look like this:

import itertools
def is_merge(s, part1, part2):
    return any(''.join(word) == s for word in itertools.permutations(part1+part2)):

Note that we do not need to build a list (no []), making this much more memory efficient. This could be achieved without using any however, by simply replacing [] in your code with (), replacing the list with a generator.

Also note that you have an extra pair of parenthesis at (itertools.p...).