Search code examples
pythonpython-itertoolsstring-comparison

Compare strings when concatenated


I am comparing 2 input strings. This is simply achieved using a one-liner function I wrote as:

from itertools import product

def com_words(str1, str2):
    return sum([i==j for i,j in product(str1.split(), str2.split())])

print(com_words("BOST BREAD", "BOST BROWN BREAD"))

However, I also want to do human-like comparison when two words are concatenated. For example, the below code results in output as ZERO, whereas I want output as TWO:

print(com_words("BOSTBREAD", " BOST BROWN BREAD"))

Except brute-force method, I am unable to create a practical and fast algorithm. Pl help.


Solution

  • Will this do?

    from itertools import product
    
    def com_words(str1, str2):
        return sum([(i in j) or (j in i) for i,j in product(str1.split(), str2.split())])
    
    print(com_words("BOSTBREAD", "BOST BROWN BREAD"))