Python – 检查字符串中所有字符的频率是否不同
在本文中,我们将学习如何查找给定字符串中每个字符的频率,然后查看给定字符串中是否存在两个或多个字符具有相同频率。我们将分两步完成此操作。在第一个程序中,我们将只找出每个字符的频率。
每个字符的频率
在这里,我们找到给定输入字符串中每个字符的频率。我们声明一个空字典,然后添加每个字符作为字符串。我们还为每个字符分配键,以创建字典所需的键值对。
示例
in_string = "She sells sea shells"
dic1 = {}
for k in in_string:
if k in dic1.keys():
dic1[k]+=1
else:
dic1[k]=1
print(dic1)
for k in dic1.keys():
print(k, " repeats ",dic1[k]," time's")输出
运行上述代码得到以下结果:
{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}
S repeats 1 time's
h repeats 2 time's
e repeats 4 time's
repeats 3 time's
s repeats 5 time's
l repeats 4 time's
a repeats 1 time's每个字符的唯一频率
接下来,我们扩展上述程序以找出每个唯一字符的频率。如果频率的唯一值大于一,则我们得出结论:并非所有字符都具有相同的频率。
示例
in_string = "She sells sea shells"
dic1 = {}
for k in in_string:
if k in dic1.keys():
dic1[k]+=1
else:
dic1[k]=1
print(dic1)
u_value = set( val for udic in dic1 for val in (dic1.values()))
print("Number of Unique frequencies: ",len(u_value))
if len(u_value) == 1:
print("All character have same frequiency")
else:
print("The characters have different frequencies.")输出
运行上述代码得到以下结果:
{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}
Number of Unique frequencies: 5
The characters have different frequencies.
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP