2016-11-09 56 views
-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') 

回答

1

只需一行做到這一點使用count上的字符串:

z= "dogdoginincatcat" 

print(z.count("cat")==z.count("dog")) 
+0

非常感謝你..我可以知道其他語言的嘗試,如C++ .. –

+0

這是一個非常不同的問題。並已經有一個答案:http://stackoverflow.com/questions/22406583/count-words-in-a-string –

+0

謝謝你的鏈接..還有更多的問題..另一個問題。我需要返回字符串「代碼」出現在給定字符串中任何位置的次數,除了我會接受任何字母爲'd',所以「應付」和「cooe」數。 count_code( 'aaacodebbb')→1個 count_code( 'codexxcode')→2 count_code( 'cozexxcope')→2 可以我有attempt..Thanks提前再次.. –

0

首先,不要使用STR(String類)作爲變量名稱。雖然Python不會在那個時候哭,但你會後悔的。

其次,它看起來並不像計數和COUNT1縮進爲一體的「如果」語句,因此您的代碼被視爲內部塊:

for i in range(len(str)) 
    if something: 
     pass 
    count = count + 1 
    if something_else: 
     pass 
    count1 = count1 + 1 

除此之外,你的代碼似乎工作

相關問題