-4
我必須從一個字符串中計算兩個單詞「貓」和「狗」。計算字符串中的兩個單詞
如果計數相等,我想返回True
否則false
。
例如,對於輸入"dogdoginincatcat"
我的方法應返回True
。
這裏是我的代碼,
def cat_dog(str):
count=0
count1=0
for i in range(len(str)):
if str[i:i+3] == 'cat':
count=count+1
if str[i:i+3] == 'dog':
count1=count+1
if count == count1:
return True
else:
return False
cat_dog('catdog')
非常感謝你..我可以知道其他語言的嘗試,如C++ .. –
這是一個非常不同的問題。並已經有一個答案:http://stackoverflow.com/questions/22406583/count-words-in-a-string –
謝謝你的鏈接..還有更多的問題..另一個問題。我需要返回字符串「代碼」出現在給定字符串中任何位置的次數,除了我會接受任何字母爲'd',所以「應付」和「cooe」數。 count_code( 'aaacodebbb')→1個 count_code( 'codexxcode')→2 count_code( 'cozexxcope')→2 可以我有attempt..Thanks提前再次.. –