Search code examples
python-3.xstringcomparison

String comparison not working as expected in python


Please correct me if I am wrong

I am trying to use the pattern matching program which I had written for one of the Leetcode's question. I would like to know what is the mistake happening at the end even though the output strings are matching for a particular input.

def wordPattern(pattern,str):
    pattern_array=[]
    str_array=[]
    
    pattern_array=[i for i in pattern]
    str_array=str.split(" ")
    
    dict={}
    
    for i in range(len(pattern_array)):
        if i in dict:
            if str_array[i]!=dict[pattern_array[i]]:
                return False
        else:
            dict[pattern_array[i]]=str_array[i]
    
    
    
    for keys, values in dict.items():
        pattern=pattern.replace(keys,values+" ")
        
    print(pattern)
    print(str)
    
    return (str==pattern)

str="dog cat cat dog"
pattern="abba"
wordPattern(pattern,str)```



Output:
dog cat cat dog
dog cat cat dog
False

Solution

    • We can also use map for solving this problem.
    • In Python, we don't have to pass " " to split like we do in Java for instance:
    class Solution:
        def wordPattern(self, pattern, sentence):
            words = sentence.split()
            return tuple(map(pattern.find, pattern)) == tuple(map(words.index, words))