简体   繁体   English

检查字符串是否与模式匹配

[英]check if string matches a pattern

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.所以我被这个问题困住了,我需要解决这个问题:给定一个单词和一个模式,我需要编写一个函数,如果单词与模式匹配,则返回 true。 The pattern looks like: "______" for example: the word "apple" will be represented as "a _ _ l " or " _ _ _ " or " pp _ e", etc... The conditions are:模式看起来像:“______”例如:单词“apple”将表示为“a _ _ l ”或“ _ _ _ ”或“ pp _ e”等......条件是:

  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例如:给定模式“d _ _ _ _ a _ _ _ _”,单词“delegating”返回True,单词“dishwasher”返回True,单词“derogation”返回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我无法导入任何模块,所以我几乎需要使用 python 的基础知识

You should be able to do this just by iterating over once and returning False when you find something that doesn't match:您应该能够通过迭代一次并在发现不匹配的内容时返回 False 来做到这一点:

def check_exact_loactions(word, pattern):
    if len(word) != len(pattern):
        return False
    for i in range(len(word)):
        if pattern[i] != '_' and word[i] != pattern[i]:
            return False
    return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM