gpt4 book ai didi

list - 查找文本中前 5 个单词长度

转载 作者:行者123 更新时间:2023-11-28 21:27:15 25 4
gpt4 key购买 nike

我正在尝试编写一个包含两个函数的程序:

  1. count_word_lengths 接受参数 text,一个文本字符串,并返回一个默认字典,记录每个单词长度的计数。调用此函数的示例:

  2. top5_lengths 采用相同的参数 text 并返回前 5 个单词长度的列表。

注意:如果两个长度有相同的频率,他们应该按降序排列。此外,如果字长少于 5 个,它应该返回一个较短的排序字长列表。

调用 count_word_lengths 的示例:

count_word_lengths("one one was a racehorse two two was one too"):
defaultdict(<class 'int'>, {1: 1, 3: 8, 9: 1})

调用 top5_lengths 的示例:

top5_lengths("one one was a racehorse two two was one too")
[3, 9, 1]

top5_lengths("feather feather feather chicken feather")
[7]

top5_lengths("the swift green fox jumped over a cool cat")
[3, 5, 4, 6, 1]

我当前的代码是这样的,似乎输出了所有这些调用,但是它没有通过隐藏测试。我没有考虑什么类型的输入?我的代码实际上运行正确吗?如果没有,我该如何解决?

from collections import defaultdict

length_tally = defaultdict(int)
final_list = []

def count_word_lengths(text):
words = text.split(' ')

for word in words:
length_tally[len(word)] += 1

return length_tally


def top5_word_lengths(text):
frequencies = count_word_lengths(text)
list_of_frequencies = frequencies.items()
flipped = [(t[1], t[0]) for t in list_of_frequencies]
sorted_flipped = sorted(flipped)
reversed_sorted_flipped = sorted_flipped[::-1]


for item in reversed_sorted_flipped:
final_list.append(item[1])

return final_list

最佳答案

需要注意的一件事是您不考虑空字符串。这将导致 count() 返回 null/undefined。您还可以在列表理解期间使用 iteritems() 从字典中获取键和值,例如 for k,v in dict.iteritems():

关于list - 查找文本中前 5 个单词长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36760676/

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