使用Python计算给定字符串中出现频率最高的全部前缀
在本教程中,我们将编写一个程序来计算并打印字母频率高于第二个字母的单词。
输入一个字符串和两个字母。将打印第一个字母频率更高的前缀。并在输出结尾显示计数。
让我们看一些例子。
输入
string:- apple alphabets:- p, e
输出
ap app appl apple 4
输入
string:- apple alphabets:- e, p
输出
0
让我们看看编写代码的步骤。
定义一个函数并在其中编写代码。
将计数初始化为0,并初始化一个空字符串。
迭代字符串。
使用字符串切片和索引获取前缀。并将其存储在空字符串中。
比较前缀中字母的频率。
如果满足条件,则打印并递增计数。
最后打印计数。
示例
# defining a function for multiple calles
def prefixes(string, _1, _2):
# count count = 0
# empty string for comparison
prefix = ""
# iterating over the string
for i in range(len(string)):
# getting the prefix from the string
prefix = string[:i + 1]
# comparing the count of alphabets in the prefix
if prefix.count(_1) > prefix.count(_2):
# printing the prefix if success
print(prefix)
# incrementing the count by 1
count += 1
# printing the count
print(f"Total prefixes matched: {count}")
if __name__ == '__main__':
# invokging the function
print(f"----------------apple p e---------------------")
prefixes('apple', 'p', 'e')
print()
print(f"----------------apple e p---------------------")
prefixes('apple', 'e', 'p')输出
如果运行上述代码,您将获得以下结果。
----------------apple p e--------------------- ap app appl apple Total prefixes matched: 4 ----------------apple e p--------------------- Total prefixes matched: 0
结论
如果您在理解代码方面遇到任何问题,请在评论区提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP