2017-04-13 21 views
-1

例如,count(「系統錯誤,語法錯誤」,「錯誤」)返回2.我不確定如何編寫此代碼。 任何幫助,不勝感激。 我嘗試啓動代碼,但是在此之後我迷路了。Python:你如何編寫一個函數來計算另一個字符串s1中指定的非重疊字符串s2的出現?

def main(): 
    s1 = input("Please enter string 1: ") 
    s2 = input("Please enter string 2: ") 
    print(count(s1,s2)) 
def count(s1, s2): # define function count that takes two strings as argument 
    count = 0 # set initial count to 0 

    while s2 < len(s1): 

main() 
+4

@neepythonhelp,爲什麼不直接使用內建函數count()。使用s1.count(s2)。 – JkShaw

+0

我想學習如何使用計數器而不是內置函數來做 – needpythonhelp

+0

對不起,我並不真正想要做什麼。你想在while循環的每次迭代中增加一個計數器嗎? –

回答

0

在這裏你去:

def count(s1, s2): # define function count that takes two strings as argument 
    counter = 0 # set initial count to 0 
    for i in range(len(s1)) : # iterate over every character 
     if s1[ i : i + len(s2) ] == s2 : # if match .. 
      counter += 1 # .. increment the counter 
    return counter 

一行代碼:

count = lambda s1, s2 : sum([ 1 for i in range(len(s1)) if s1[ i : i + len(s2) ] == s2 ]) 
0

更優化的代碼考慮的聲明「非重疊的字符串」

s1 = "This is the code th fwefthe" 
s2 = "th" 

i = 0 
len_s1, len_s2 = len(s1), len(s2) 

count = 0 
while i < len_s1: 
    if s1[i:i+len_s2] == s2: 
    count += 1 
    i += len_s2 
    else: 
    i += 1 

你可以看到當我得到一個匹配時,計數器增加len(s2)而不是遞增1。它確實提高了性能。

+0

您還可以提高程序的性能通過將's1'和's2'的長度保存在變量中,並使用那些來代替'len(string)',因爲這些字符串的值永遠不會改變。這將節省時間,因爲Python不必一直重複計算每個字符串的長度。 –

+0

@algerbrex,感謝您的建議,編輯了代碼。 – JkShaw

1
  1. 您可以分割的文本,把它放在一個數組:

    s= "This should work work" 
    
    words = s.split() 
    
  2. 你算的話:

    words.count("work") 
    
+0

感謝legoscia :) –

相關問題