2014-12-02 69 views
-3

我寫簡單的Python代碼:編程錯誤

Question: 
Given a list of strings, return the count of the number of 
# strings where the string length is 2 or more and the first 
# and last chars of the string are the same. 

解決我的工作:

def match_ends(words): 
    for items in words: 
     count = 0 
     los = len(items) 
     first_char= items[0] 
     last_char= items[los-1] 
     if los >=2 and first_char is last_char: 
      count = count+1 
     else: 
      count = count 

    print count 
    return 

def main(): 
    print 'match_ends' 
    match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']) 

我不斷獲取答案爲1的時候,我覺得它是沒有完全循環。錯誤在哪裏

+5

我不喜歡的樣子那是'是'。嘗試使用'=='代替。哦,並且在循環之外移動count == 0。 – Kevin 2014-12-02 18:41:33

+4

你是否打算在循環的每次迭代中將'count'重置爲'0'? – Celeo 2014-12-02 18:42:43

+2

'else:count = count'沒用。 – user2097159 2014-12-02 18:43:33

回答

3

之前另一種更簡潔的方式來做到這僅僅是:

sum(1 for s in words if len(s) > 1 and s[0] == s[-1]) 
3

我將使用==運算符來比較字符而不是is關鍵字。您也可以使用[-1]索引從後面切片以獲取最後一個字符,而不是本質上做[len-1]。您還重置count0在每個循環的開始(也count已經是一個函數名,儘量避免命名具有相同名稱的變量)

話雖這麼說,這裏是有一些相同的想法爲了可讀性而修改以上內容。

def matches(words): 
    total = 0 
    for word in words: 
     if (len(word) > 1) and (word[0] == word[-1]): 
      total += 1 
    return total 

>>> matches(['aba', 'xyz', 'aa', 'x', 'bbb']) 
3 
1

的原因是,您需要將數= 0線for items in words: