所以這是我的代碼
def count_occurrences(sub, s):
if len(s) == 0:
return 0
else:
if str(sub) in str(s) and str(sub) == str(s):
return 1 count_occurrences(sub, s[1:])
else:
return count_occurrences(sub, s[1:])
print(count_occurrences('ill', 'Bill will still get ill'))
我相信if str(sub) in str(s) and str(sub) == str(s):當我運行除錯器 UI 時,這個陳述句會讓我失望。如果我只是把if str(sub) in str(s)它給我一個數字,但它不是我想要的數字 4。
uj5u.com熱心網友回復:
您的代碼不能正常作業,因為僅當您找到將導致程式在同一位置查找子字串的子字串時才跳過一個字符,而您必須在子字串第一次出現后跳至索引。此代碼將作業
def count_occurences(s, sub):
if len(s) == 0:
return 0
else:
ind = s.find(sub)
if ind>=0:
return 1 count_occurences(s[ind 1:], sub)
else:
return 0
我在索引中添加了 1,因為在“生病”的情況下,find()會給我字母 'i' 的索引,所以如果我給s[ind 1:]它會洗掉第一個 'l' 之前的所有字符,即包括 'i',所以下一次迭代不會在與以前相同的地方找到“生病”,這導致兩次計算相同的出現。
uj5u.com熱心網友回復:
你的條件str(sub) == str(s)永遠不會為真,除非子字串在最后。您必須比較字串的開頭(與子字串的長度相同)而不是在任何位置搜索它,否則您將多次計算相同的匹配項。此外,如果您已經在處理字串,則不需要使用 str() 。
def count_occurrences(sub, s):
if len(sub)>len(s): return 0
return s.startswith(sub) count_occurrences(sub,s[1:]) # True is 1
輸出:
print(count_occurrences('ill', 'Bill will still get ill'))
4
請注意,我假設您要計算重疊的子字串。例如: 'ana' 在 'banana' 中計數為 2。
uj5u.com熱心網友回復:
您可以使用str.split()和.count()用于計數,如下所示:
def count_occurrences(sub, s):
if not(len(s.strip())):
return 0
splt_s = s.split()
return (splt_s[0].count(sub)) count_occurrences(sub, ' '.join(splt_s[1:]))
輸出:
>>> count_occurrences('ill', 'Bill will still get ill')
4
>>> count_occurrences('ill', 'Billwillstillgetill Billwillstillgetill ')
8
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/334070.html
