0

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

2 Answers 2

1
  • 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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this solution Emma, it was useful. To my situation, the below code snippet as also apt.
0

Found the answer to this as I added extra space at the end for the string as I mentioned

pattern=pattern.replace(keys,values+" "), that extra space added for the string at the end. So, I shall remove it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.