Python 计算字符串中最小长度的唯一字
我必须写一个函数,它包含两个变量,一个句子和一个数字。函数应返回字符串中大于或等于数字的唯一字数。示例结果应为:Python 计算字符串中最小长度的唯一字,python,function,loops,for-loop,Python,Function,Loops,For Loop,我必须写一个函数,它包含两个变量,一个句子和一个数字。函数应返回字符串中大于或等于数字的唯一字数。示例结果应为: >>> 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 sentenc
>>> 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:
现在我不知道如何继续我的解决方案。有人能帮我吗?试试这个:
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
或:
试试这个:
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
或:
这里有一个提示:
>>> 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
这里有一个提示:
>>> 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
我喜欢第一个解决方案,但它将返回7而不是6,因为我相信“blue”和“blue”是两个不同的词。如何解决这个问题?@Artsiom Rudzenka使用string.标点符号,您忘记了所有这些:“$\”和+*/;:=@非常感谢你@ArtsiomRudzenka首先做一套怎么样?无论如何,它也不需要是一个列表。这一行:w=w.strip绝对没有效果,因为您正在剥离任何内容。我喜欢第一个解决方案,但它将返回7而不是6,因为我相信“蓝色”和“蓝色”是两个不同的词。如何解决这个问题?@Artsiom Rudzenka使用string.标点符号,您忘记了所有这些:“$\”和+*/;:=@非常感谢你@ArtsiomRudzenka首先做一套怎么样?无论如何,它也不需要是一个列表。这一行:w=w.strip绝对没有效果,因为您没有剥离任何内容