gpt4 book ai didi

python - 查找字符串列表中最独特的字符

转载 作者:行者123 更新时间:2023-12-02 08:10:49 25 4
gpt4 key购买 nike

最近加入了 python 代码俱乐部,所以不是学校作业。

任务:

Write a function coolest_word(words) that returns the coolest word if it exists.

The coolness is defined by how many unique characters a word has.

For example the word "decomposition" has a 10 unique letters. Your job is to find from the given list of words the coolest word and return it.

If the list is empty, return None. If there is a tie, return one of the words.

到目前为止我的解决方案:

words = ['expectation', 'discomfort', 'half', 'decomposition']
def coolest_word(words):
length = 0
unique = ['']
for i in words:
if (len(words) != 0 and len(set(i)) > length):
length = len(set(i))
unique[0] = i
else:
unique[0] = ('None')
return(unique)
print(coolest_word(words))

我选择将 list 更改为 set,然后将 set 的唯一字符相互比较。由于 set 没有考虑重复变量,这似乎是一个好主意。

每当 for 循环找到更长的集合(具有更多变量)时,它就会被覆盖为唯一的集合以供内存并稍后调用。

现在的问题是,如果给定的列表为空,唯一的返回[''],我不明白为什么。

如第二部分所示,如果列表为空,我希望唯一的被覆盖,但它不会这样做。

有什么想法吗?

最佳答案

max的简单应用具有keydefault

def coolest_word(words):
return max(words, key=lambda w: len(set(w)), default=None)

演示:

>>> coolest_word(['expectation', 'discomfort', 'half', 'decomposition'])
'decomposition'

>>> [coolest_word([])] # Wrap in a list because None by itself doesn't get printed
[None]

关于python - 查找字符串列表中最独特的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60409794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com