def main():
x = {}
for word in sentence:
x[word] = sentence.count(word)
for letter in sorted(x):
print (letter + ': ' + str(x[letter]))
sentence=input("Enter a sentence: ")
main()
def main():
x = {}
for word in sentence:
x[word] = sentence.count(word)
sorted_letters = sorted(x, key=lambda v: x[v])
for letter in sorted_letters:
print (letter + ': ' + str(x[letter]))
print('Most used letter =', sorted_letters[-1])
sentence=input("Enter a sentence: ")
main()
样本输入/输出:
Enter a sentence: Hello World!
H: 1
e: 1
: 1
W: 1
r: 1
d: 1
!: 1
o: 2
l: 3
Most used letter = l
def main():
x = {}
for word in sentence:
if word != " ":
x[word] = sentence.count(word)
maximum_occurrences = max(x.values())
for letter,occurrences in x.items():
if occurrences == maximum_occurrences:
print("Max value found, the letter "+ letter + " was found " + str(occurrences)+ " times.")
sentence=input("Enter a sentence: ")
main()
>>>> Enter a sentence: This is simply a test
>>>> Max value found, the letter s was found 4 times.
基本上,它返回任何出现次数最多的字母。请注意,这会处理多个字母出现次数相同的情况。你知道吗
编辑
另外请注意,我添加了if word != " ":,因为您的初始代码将空格视为可能不是您想要的单词。你知道吗
只需按值对字母排序,然后写入排序数组的最后一个成员:
样本输入/输出:
因此,要从dict
x
中找到最大使用量的单词,可以使用operator
,比如-但这只会给你n个单词中有一个相等的,即最大值
如果你正在寻找一个易于阅读的解决方案,接近你想要实现的,那就可以了
基本上,它返回任何出现次数最多的字母。请注意,这会处理多个字母出现次数相同的情况。你知道吗
编辑
另外请注意,我添加了
if word != " ":
,因为您的初始代码将空格视为可能不是您想要的单词。你知道吗相关问题 更多 >
编程相关推荐