提问人:amoez200 提问时间:11/15/2023 最后编辑:Timur Shtatlandamoez200 更新时间:11/15/2023 访问量:100
找出句子或单词中重复次数最多的字符
Find which character is repeated most times in a sentence or a word
问:
most = 0
list_of_letters = []
def remove(string):
return "".join(string.split())
sentence = input('Enter a sentence or a word: ')
new = remove(sentence)
new = new.lower()
for i in new:
rep = 0
for n in new:
if i == n:
rep += 1 ###hhello
if rep > most:
list_of_letters = [i]
most = rep
elif rep == most:
for z in list_of_letters:
if i == z:
break
else:
list_of_letters.append(i)
print(list_of_letters)
for index in list_of_letters:
print(index, end=(" "))
print(f'is repeated the most at {most}')
当尝试将相同重复次数的字符附加到 的数组中时,问题就来了。如果它已经在数组中,则不应将其附加到数组中,但它会做很多次。list_of_letters
答:
0赞
UpAndAdam
11/15/2023
#1
对于一个简单的问题来说太复杂了,只需使用字典来计算出现次数:
sentence = input("enter a sentence or a word: ")
max = None
max_count = 0
letters = dict()
for letter in sentence:
if not letter.isalpha():
continue
my_letter = letter.lower()
count = 1
if my_letter not in letters:
letters[my_letter] = 1
# count is already set to 1
else:
count = letters[my_letter] + 1
letters[my_letter] = count
if count > max_count:
max_count = count
max = my_letter
print(f'{max} is repeated the most at {max_count}')
评论
0赞
Mark Reed
11/15/2023
你的变量没有做任何有用的事情。为什么不只是,或者,甚至更好,?您也可以使用默认值为 0 的 a,而不需要检查。count
letters[my_letter] = letters[my_letter] + 1
letters[my_letter] += 1
defaultdict
not in
0赞
UpAndAdam
11/15/2023
count
变量用于避免额外的回溯来跟踪,因此我不必在最后对字典进行另一次迭代来查找最大计数字母。max_count
n
0赞
Mark Reed
11/15/2023
当您与 进行比较时,您要与之进行比较的值是以任何一种方式进行的。你不需要一个单独的变量来保存它。max_count
letters[my_letter]
0赞
UpAndAdam
11/15/2023
是的,我可以使用 defaultdict,但我试图让它对初学者来说尽可能简单。你的其他建议是句法糖。 和我写的没什么不同。你争论的观点在代码执行中根本没有区别。+= 1
0赞
JonSG
11/15/2023
我不确定指出他们当前解决方案的复杂性是否会有所帮助。我敢肯定,如果他们知道如何做,他们会写出一个更简单的解决方案。我要强调的是,python 通常为许多常见任务提供简单/干净的替代方案。
2赞
Timur Shtatland
11/15/2023
#2
使用集合。计数
器来计算字母。使用列表推导式仅从小写句子中选择字母。请注意,按出现顺序仅返回 1 个最常出现的字符。因此,在下面的示例中,它打印但不打印。但是,如果您想要所有最常见的字母,那么访问这些元素是微不足道的。most_common(1)
o
b
Counter
from collections import Counter
sentence = input('Enter a sentence or a word: ')
letters = [c for c in sentence.lower() if c.isalpha()]
cnt = Counter(letters)
print(f"letters: occurrences: {cnt}")
print(f"most common: {cnt.most_common(1)}")
例:
输入:
Enter a sentence or a word: foo bbar.
输出:
letters: occurrences: Counter({'o': 2, 'b': 2, 'f': 1, 'a': 1, 'r': 1})
most common: [('o', 2)]
评论
1赞
Mark Reed
11/15/2023
类似的东西将显示所有与最常见的字母相关的字母。mc = cnt.most_common(1); print(f'most common: {[p for p in cnt.items() if p[1] == mc[0][1]]}')
1赞
JonSG
11/15/2023
#3
在考虑如何帮助修复当前代码时,我会考虑使用来帮助积累不同字母列表,并避免我们已经完成的工作。in
if i in list_of_letters:
continue
else:
list_of_letters.append(i)
这样一来,我们就可以在for循环的末尾删除一大块代码。
完整示例:
def remove(string):
return "".join(string.split())
sentence = input('Enter a sentence or a word: ')
new = remove(sentence)
new = new.lower()
list_of_letters = []
most_letter = ""
most = 0
for i in new:
## ---------------
## if we already counted this letter we can skip doing so again
## ---------------
if i in list_of_letters:
continue
## ---------------
## ---------------
## ---------------
## If we get here, this is a new letter we have not seen before
## ---------------
## ---------------
list_of_letters.append(i)
## ---------------
## Count how many times letter "i" appears in "new"
## ---------------
rep = 0
for n in new:
if i == n:
rep += 1
## ---------------
## ---------------
## If the prior count "rep" is more than are current max
## ---------------
if rep > most:
most_letter = i
most = rep
## ---------------
## ---------------
## This count is less than some prior count
## we can ignore it
## ---------------
#elif rep == most:
# for z in list_of_letters:
# if i == z:
# break
# else:
# list_of_letters.append(i)
## ---------------
print(f"In the phrase '{sentence}'")
print(f"The most common letter was: '{most_letter}' found {most} times")
print(f"Distinct Letters: '{''.join(list_of_letters)}'")
如果你运行它并在出现提示时输入“hello world”,你将返回:
In the phrase 'hello world'
The most common letter was: 'l' found 3 times
Distinct Letters: 'helowrd'
替代方法:
您还可以查看许多简单的改进。例如,调用 to 将为您提供不同的字母,并计算该字母在 中出现的次数。list_of_letters = list(set(new))
rep = new.count(i)
i
new
但是,要同时获得不同的字母列表及其计数,我们可以利用 .它将或多或少地为我们完成所有工作。collections.Counter
import collections
sentence = input('Enter a sentence or a word: ')
## -----------
## make someone else do the work for us
## -----------
counted_letters = collections.Counter(sentence.lower().replace(" ", ""))
## -----------
list_of_letters = list(counted_letters.keys())
most_letter, most = counted_letters.most_common(1)[0]
print(f"In the phrase '{sentence}'")
print(f"The most common letter was: '{most_letter}' found {most} times")
print(f"Distinct Letters: '{''.join(list_of_letters)}'")
评论
i not in list_of_letters
else
for
if
i
most
i
list_of_letters
most
set(new)
list_of_letters = [x for i, x in enumerate(new) if x not in list(new)[:i]]