簡體   English   中英

將四個字母的單詞與一個任意字符匹配

[英]matching four letter word with one arbitrary character

您會得到一個由小寫字母組成的字符串str。 您需要計算單詞doge在字符串中出現的次數。 同樣, dogeg可以由z中的任何字母替換,因此dope也有效。

這個問題出現在我正在查看的網站上。 由於該站點沒有選擇來討論問題,因此我在這里尋求幫助:

def doge_count(str):
    count=0
    for i in range (0,len(str)):
        if (i=="d" and i+1=="o" and i+3=="e"):
            count= count+1
    return count

輸入:

2
dog
dogedopedose

您的輸出是:

0
0

您的邏輯實際上很接近。 唯一的問題是i是整數,因此比較i=="d" and i+1=="o" and i+3=="e"始終為false。 i==0 ,但是0 !="d" ,您將期望獲得匹配。

解決方法是使用i來索引str ,就像您想要的那樣:

if str[i:i+2] == "do" and str[i+3] == "e":

您還將希望以不會超出字符串結尾的方式循環:

for i in range(len(str) - 3):

一個更可靠的解決方案是使用正則表達式 以下模式匹配您想要的字符串:

do[a-z]e

您可以使用re.findall計算出現re.findall

count = len(re.findall('do[a-z]e]', str))

代碼不起作用的原因是,您正在檢查以下代碼行中的整數是否等於字符串: i=="d"

這行代碼: for i in range (0, len(str))返回從0length_of_string - 1整數。

您需要做的是檢查第i個位置的字符串是否等於所需的攪拌量。 像: str[i] == "d"

這將是您邏輯中代碼的正確版本:

def doge_count(str):
    count = 0
    for i in range(0, len(str)-3):
        if str[i] == "d" and str[i+1] == "o" and str[i+3] == "e":
            count = count+1
    return count


print(doge_count('dog'))
print(doge_count('dogedopedose'))

您可以使用列表理解:

>>> [s[i:i+4] for i in range(len(s)-3) if s[i:i+2]=='do' and s[i+3]=='e']
['doge', 'dope', 'dose']
test_patterns='do[a-z]e'
phrase = 'this is doze but Doze again dore then dofe'
list_matches = re.findall(test_patterns,phrase.lower())
print('The number of d(any alphabet)ze : {frequency}'.format(frequency=len(list_matches)))

查找列表中的模式的全部匹配項,然后獲取列表的計數,您將獲得總督或自由度或任何此類數字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM