2013-04-17 119 views
1

我必須編寫一個函數,它需要2個變量,一個句子和一個數字。函數應該返回字符串中等於或大於數字的唯一字的數量。這個例子的結果應該是:計算字符串中最小長度的唯一字

>>> unique_func("The sky is blue and the ocean is also blue.",3) 
    6 

所有我能想到的解決方法是

def unique_func(sentence,number): 
    sentence_split = sentence.lower().split() 
    for w in sentence_split: 
     if len(w) >= number: 

現在我不知道如何繼續我的解決方案。誰能幫我?

回答

2

試試這個:

from string import punctuation 

def unique_func(sentence, number): 
    cnt = 0 
    sentence = sentence.translate(None, punctuation).lower() 
    for w in set(sentence.split()): 
     if len(w) >= number: 
      cnt += 1 
    return cnt 

或者:

def unique_func(sentence, number): 
    sentence = sentence.translate(None, punctuation).lower() 
    return len([w for w in set(sentence.split()) if len(w) >= number]) 
+0

我喜歡的第一個解決方案,但它會返回7而不是6因爲我相信'藍'和'藍'是兩個不同的單詞。如何解決這個問題? –

+0

@AlexaElis固定 –

+0

@Artsiom Rudzenka使用'string.punctuation',你忘了所有這些:''#'%$''&)(+*/;:= @ [] \\ _ ^'{} |〜'' – jamylak

1

這裏是一個暗示:

>>> set('The sky is blue and the ocean is also blue'.lower().split()) 
{'is', 'also', 'blue', 'and', 'the', 'sky', 'ocean'} 
>>> len(set('The sky is blue and the ocean is also blue'.lower().split())) 
7 
1
>>> from string import punctuation 
>>> def unique_func(text, n): 
     words = (w.strip(punctuation) for w in text.lower().split()) 
     return len(set(w for w in words if len(w) >= n)) 


>>> unique_func("The sky is blue and the ocean is also blue.",3) 
6 
相關問題