2016-09-20 86 views
-7
def countConsonant (s): 

    """Count consonants. 

    'y' and 'Y' are not consonants. 

    Params: s (string) 
    Returns: (int) #consonants in s (either case) 
    """ 

    # do not use a brute force solution: 
    # think of a short elegant solution (mine is 5 lines long); 
    # do not use lines longer than 80 characters long 

    # INSERT YOUR CODE HERE, replacing 'pass' 
    countConsonant = 0 
    for index in s: 
     if index == 'bcdfghjklmnpqrstvwxyz': 
      countConsonant += 1 
    return countConsonant 

print (countConsonant ('"Carpe diem", every day.')) # should return 8 
+6

問題尋求幫助調試(「**爲什麼不是這個代碼的工作?**」)必須包括所期望的行爲,一個特定的問題或錯誤,並在最短的代碼要重現**在問題本身**。沒有**明確問題陳述**的問題對其他讀者沒有用處。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – Biffen

回答

3

==檢查是否相等,這可能不是你想要的。您必須使用in運算符來檢查成員資格,在這種情況下,字符串中的字符的成員身份。它遵循以下一般語法:

if x in y: 

哪裏x是,如果成員存在於y正在檢查的操作數或一個。將其應用於這種情況下,更換您的if聲明如下:

if index in 'bcdfghjklmnpqrstvwxyz': 

這將隨後檢查某些字符是在給定的輔音串。另外,有一點需要注意,你只能檢查小寫字母。這意味着CCarpe diem被忽略給人9.結果忽略大小寫嘗試:

if index.lower() in 'bcdfghjklmnpqrstvwxyz': 

檢查時,這將使得該字符串小寫。

0

隨着你迭代s中的所有字符的聲明

for index in s:

。所以條件

if index == 'bcdfghjklmnpqrstvwxyz':

以往的計算結果爲False和功能在每個情況下返回0。

要檢查字符串中字符的成員資格,您需要使用in運算符而不是==,該運算符會檢查值的相等性。

如果您的算法與案例無關,則可以將輸入小寫或將所有對應的大寫字母添加到字符串'bcdfghjklmnpqrstvwxz'。由於根據您的要求,'y''Y'不是輔音,因此您需要從字符串'bcdfghjklmnpqrstvwxyz'中刪除y。和你的最終代碼是

def countConsonant (s): 

    """Count consonants. 

    'y' and 'Y' are not consonants. 

    Params: s (string) 
    Returns: (int) #consonants in s (either case) 
    """ 
    countConsonant = 0 
    for index in s.lower(): 
     if index in 'bcdfghjklmnpqrstvwxz': 
      countConsonant += 1 
    return countConsonant 

print (countConsonant ('"Carpe diem", every day.')) # should return 8