Home > Enterprise >  check if string matches a pattern
check if string matches a pattern

Time:11-01

So I am stuck with this problem I need to solve this question: given a word and a pattern, I need to write function that return true if the word matches the pattern. The pattern looks like: "______" for example: the word "apple" will be represented as "a _ _ l " or " _ _ _ " or " p p _ e", etc... The conditions are:

  1. The word needs to contain the exact characters revealed (=not "_") at the same index as in the pattern
  2. the revealed characters in the pattern can't appear in other place in the word other than the same index

for example: given the pattern "d _ _ _ _ a _ _ _ _" for the word "delegating" return True for the word "dishwasher" return True for the word "derogation" return True

I wrote this code:

def check_exact_locations(word, pattern):
word_list = list(word)
pattern_list = list(pattern)
for i in range(len(word_list)):
    if word_list[i] in pattern:
        for j in range(1, len(pattern_list)):
            if pattern_list[j] != "_":
                if pattern_list[j] != pattern_list[j-1]:
                    if word_list[i] == pattern_list[j] and i != j:
                        return False
return True

I can't import any module so I pretty much need to use python's basics

CodePudding user response:

You should be able to do this just by iterating over once and returning False when you find something that doesn't match:

def check_exact_loactions(word, pattern):
    if len(word) != len(pattern):
        return False
    for w, p in zip(word, pattern):
        if p != '_' and w != p:
            return False
    return True

(Edited with @Tomerikoo's suggestion)

  • Related