2015-05-23 20 views
-3

在任何地方字符串「代碼」的次數返回的字符串"code"隨時隨地出現在 給定的字符串,除了我們會接受任何字母爲'd'的次數,所以 "cope""cooe"計數。返回出現的給定的字符串

import re 


def count_code(str): 
    exp = '^co[a-z|A-Z]e$' 
    count = 0 
    for i in range(len(str) - 1): 
     if re.match(exp, str[i:i + 4]): 
      count = count + 1 

    return count 

print count_code('aaacodebbb') # prints 1 
print count_code('codexxcode') # prints 2 
print count_code('cozexxcope') # prints 2 

是否有實現這一目標,而無需使用正則表達式的任何其他方式:

我已經使用正則表達式下面的代碼實現這一點?

+0

您的正則表達式變量效率低下。查看[re.findall](https://docs.python.org/2/library/re.html?highlight=re.findall#re.findall),並將其與[len](https:/ /docs.python.org/2/library/functions.html?highlight=len#len)。 – Phillip

+0

*「有沒有其他方式......」 - 是的,當然有。你有真正的問題嗎? – jonrsharpe

+0

@Phillip,謝謝,也會試試。 –

回答

0

一種方法是你可以盡一切可能的字符串與合作* e其中*是任何字母

x=["co"+i+"e" for i in string.lowercase] 

然後遍歷

for i in x: 
    if i in <your string>: 
     count+=<your string>.count(i) 
+0

如果是'codexxxcode'會怎麼樣?那隻會得到一個。 –

+0

您可以使用str.count()來計算所有非重疊事件的實例。 – Sandman

+0

我已經編輯它相應。 @重要性。 – therealprashant

0

你可以試試這個:

def count_code(str): 
    x=["co"+i+"e" for i in str.lower()] 
    count = 0 
    index = 0 
    for i in x: 
     if i in str[index:]: 
      index = str.find(i)+1 
      count+=1 
    return count 

print count_code('aaacodebbb') # prints 1 
print count_code('codexxcode') # prints 2 
print count_code('cozexxcope') # prints 2  
-1
def count_code(str): 
    a = 0 
    for i in range(len(str) - 3): 
    if str[i:i+2] + str[i+3] == 'coe': 
     a += 1 
    return a 
+0

介意加幾句話來解釋代碼? – CinCout

相關問題