编写一个程序读取未指定个数的字符串(以空格隔开),找出出现次数最多的字符串及其出现次数。 如果出现次数最多的有多个字符串,按照字符串升序输出所有出现次数最多的字符串。
时间: 2024-01-14 21:42:40 浏览: 17
可以使用一个字典来记录每个字符串出现的次数,然后再遍历字典找出出现次数最多的字符串及其出现次数。
代码如下:
```python
string_list = input().split()
string_dict = {}
# 统计每个字符串出现的次数
for s in string_list:
if s in string_dict:
string_dict[s] += 1
else:
string_dict[s] = 1
# 找出出现次数最多的字符串及其出现次数
max_count = 0
max_strings = []
for s, count in string_dict.items():
if count > max_count:
max_count = count
max_strings = [s]
elif count == max_count:
max_strings.append(s)
# 按照字符串升序输出所有出现次数最多的字符串
max_strings.sort()
for s in max_strings:
print(s, max_count)
```
假设输入为:"hello world hello python world python python",输出为:
```
python 3
```
相关问题
编写个程序读取未指定个数的字符串(以空格隔开),找出出现次数最多的字符串及其出现次数。 如果出现次数最多的有多个字符串,按照字符串升序输出所有出现次数最多的字符串。
可以使用一个字典来记录每个字符串出现的次数,然后找到出现次数最多的字符串和它的出现次数。代码如下:
```python
s = input().split() # 读取输入的字符串
counts = {} # 用字典记录每个字符串出现的次数
max_count = 0 # 出现次数最多的字符串的出现次数
# 遍历每个字符串并记录出现次数
for word in s:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
# 更新出现次数最多的字符串的出现次数
if counts[word] > max_count:
max_count = counts[word]
# 找到出现次数最多的字符串并按照字符串升序输出
result = []
for word, count in counts.items():
if count == max_count:
result.append(word)
result.sort()
print(result[0], max_count)
```
这个程序首先读取输入的字符串并用字典记录每个字符串出现的次数,然后找到出现次数最多的字符串并按照字符串升序输出。注意如果出现次数最多的字符串有多个,需要把它们都输出。
问题描述】 编写一个程序读取未指定个数的字符串(以空格隔开),找出出现次数最多的字符串及其出现次数。 如果出现次数最多的有多个字符串,按照字符串升序输出所有出现次数最多的字符串。 例如输入abc bcd abc bcd bbb,那么字符串"abc"和"bcd"出现的次数最多,2次,先输出abc 2,再输出bcd 2。 【样例输入】 abc bcd abc bcd bbb 【样例输出】 abc 2 bcd 2 【样例说明】 输入为一行,分别是以空格分隔开的未指定个数的字符串 输出为不定行,按照字符串升序排列的出现次数最多的字符串及其出现次数
好的,我已经明白了你的问题。下面是一个简单的 Python 代码实现:
```python
from collections import Counter
# 读取输入字符串
s = input().strip()
# 统计出现次数
cnt = Counter(s.split())
# 找到出现次数最多的字符串
max_cnt = max(cnt.values())
# 输出出现次数最多的字符串及其出现次数
for key, value in sorted(cnt.items()):
if value == max_cnt:
print(key, value)
```
这个程序首先读取输入字符串,并使用 Python 的 `collections` 模块中的 `Counter` 类来统计每个字符串出现的次数。然后,它找到出现次数最多的字符串,并按照字符串升序输出所有出现次数最多的字符串。