2012-10-21 37 views
-1
# 5.- match_ends 
# 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. 
# Note: python does not have a ++ operator, but += works. 
#  For example, the result of n = n + 1 can be also achieved by n += 1. 



def match_ends(words): 
    # +++your code here+++ 
    if len(words)>=2: 
    return words[0]and words[-1:]==words[-1:] 
    words+=words 

你們認爲我做錯了什麼,我應該如何改善呢?python程序與match_ends

這裏的結果:

match_ends 
    X got: True expected: 3 
    X got: '' expected: 2 
OK got: True expected: 1 
+0

聽起來像一個家庭作業,並且大部分代碼都是錯誤的。例如,你認爲'len(文字)'做了什麼?什麼是'字[0]'?注意:有一個交互式shell,你可以嘗試大部分的東西。 –

+0

其谷歌python類鍛鍊:) –

回答

1
def match_ends(words): 
    word_count=len(words) 
    results=[] 
    for x in words: 
     if len(x)>2 and x[0]==x[len(x)-1]: 
      results.append(x) 
    return word_count,results 

word_list=["hello","wow"] 
matched_words=match_ends(word_list) 
print matched_words 

這應該爲你工作:)

如果你想讓它多一點Python的,你可以這樣做:

def match_ends(words): 
    word_count=len(words) 
    results=[x for x in word_list if len(x)>2 and x[0]==x[len(x)-1]] 
    return word_count,results 
0

更簡化的方法:

def match_ends(words): 
    count = 0 
    for i in words: 
    if len(i) >= 2 and i[-1] == i[0]: 
     count = count + 1 
    return count