所以我被這個問題困住了,我需要解決這個問題:給定一個單詞和一個模式,我需要編寫一個函數,如果單詞與模式匹配,則返回 true。模式看起來像:“______”例如:單詞“apple”將表示為“a _ _ l ”或“ _ _ _ ”或“ pp _ e”等......條件是:
例如:給定模式“d _ _ _ _ a _ _ _ _”,單詞“delegating”返回True,單詞“dishwasher”返回True,單詞“derogation”返回True
我寫了這段代碼:
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
我無法導入任何模塊,所以我幾乎需要使用 python 的基礎知識
您應該能夠通過迭代一次並在發現不匹配的內容時返回 False 來做到這一點:
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
(根據@Tomerikoo 的建議編輯)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句