1

我必须编写一个函数,它需要两个变量,即一个句子和一个数字。该函数应返回字符串中等于或大于该数字的唯一词的数量。示例结果应该是:

>>> 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:

现在我不知道如何继续我的解决方案。谁能帮我?

4

3 回答 3

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])
于 2013-04-17T04:55:38.287 回答
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
于 2013-04-17T04:56:21.767 回答
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
于 2013-04-17T04:58:50.693 回答