请用python编写程序统计1行字符串中: 不同字符的个数。 每种字符出现的次数。 函数接口定义: Freq(line) 函数功能:该函数统计不同字符出现的次数,并最后按照字符升序进行输出。输出格式见输出样例。 参数说明:line为需要统计的字符串。 裁判测试程序样例: /* 请在这里填写答案 */ line = input() Freq(line) 输入样例: abc 123 adex!!! 输出样例: 11 = 2 ! = 3 1 = 1 2 = 1 3 = 1 a = 2 b = 1 c = 1 d = 1 e = 1 x = 1 输出格式说明: 第1行输出不同字符的个数。 **=**两边应有空格。 上述输出样例中第2行的字符是空格。 输出按照字符升序排列。
时间: 2024-02-20 22:00:00 浏览: 30
以下是 Python 代码实现:
```python
def Freq(line):
freq_dict = {}
for char in line:
if char in freq_dict:
freq_dict[char] += 1
else:
freq_dict[char] = 1
sorted_chars = sorted(freq_dict.keys())
print(len(sorted_chars), end=" = ")
print(len(line))
for char in sorted_chars:
print(char, end=" = ")
print(freq_dict[char])
```
使用 `input()` 函数获取输入字符串,然后调用 `Freq()` 函数即可。
例如:
```python
line = input()
Freq(line)
```
输入:
```
abc 123 adex!!!
```
输出:
```
11 = 11
! = 3
1 = 1
2 = 1
3 = 1
a = 2
b = 1
c = 1
d = 1
e = 1
x = 1
```
相关问题
6-2 使用python编写程序统计1行字符串中: 不同字符的个数。 每种字符出现的次数。 函数接口定义: Freq(line) 函数功能:该函数统计不同字符出现的次数,并最后按照字符升序进行输出。输出格式见输出样例。 参数说明:line为需要统计的字符串。
def Freq(line):
# 统计每种字符出现的次数
freq_dict = {}
for char in line:
if char in freq_dict:
freq_dict[char] += 1
else:
freq_dict[char] = 1
# 统计不同字符的个数
char_count = len(freq_dict)
# 按照字符升序输出结果
freq_list = sorted(freq_dict.items(), key=lambda x: x[0])
for char, count in freq_list:
print("{}:{}".format(char, count))
print("不同字符的个数为:{}".format(char_count))
jmu-java&python-统计字符个数 分数 5 作者 郑如滨 单位 集美大学 编写程序统计1行字符串中: 不同字符的个数。 每种字符出现的次数。 函数接口定义: Freq(line) 函数功能:该函数统计不同字符出现的次数,并最后按照字符升序进行输出。输出格式见输出样例。 参数说明:line为需要统计的字符串。
好的,下面是该函数的实现:
```python
def Freq(line):
freq_dict = {} # 统计不同字符出现的次数的字典
for char in line:
if char in freq_dict:
freq_dict[char] += 1
else:
freq_dict[char] = 1
freq_list = sorted(freq_dict.items(), key=lambda x: x[0]) # 将字典按照字符升序排序
print(len(freq_dict)) # 输出不同字符的个数
for item in freq_list:
print(item[0], item[1]) # 输出每种字符出现的次数
```
该函数接受一个字符串类型的参数 `line`,并通过遍历字符串中的每个字符来统计不同字符出现的次数。具体地,我们使用一个字典类型的变量 `freq_dict` 来记录每个字符出现的次数,然后将其按照字符升序排序后输出。
需要注意的是,该题目需要我们输出不同字符的个数,而不是字符串的长度。因此,在统计字符出现次数的时候,我们需要使用字典类型,并统计字典中不同键的个数。
以下是该函数的使用示例:
```python
line = "123abcABC"
Freq(line)
# 输出:
# 6
# 1 1
# 2 1
# 3 1
# A 1
# B 1
# C 1
```