Reputation: 21
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
Upvotes: 0
Views: 195
Reputation: 27723
map
for solving this problem." "
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))
Upvotes: 1
Reputation: 21
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.
Upvotes: 0