首页 文章资讯内容详情

使用Python以最大频率计数给定字符串中的所有前缀

2026-06-04 1 花语

在本教程中,我们将编写一个程序,该程序以比第二个字母更高的字母频率来计数和打印单词。

取一个字符串和两个字母。第一个字母的频率较高的前缀将被打印。并在输出末尾显示计数。

让我们看一些例子。

输入项

string:- apple alphabets:- p, e

输出结果

ap app appl apple 4

输入项

string:- apple alphabets:- e, p

输出结果

0

让我们看看编写代码的步骤。

定义一个函数并在其中编写代码。

将count初始化为0和一个空字符串。

遍历字符串。

使用字符串切片和索引获取前缀。并将其存储在一个空字符串中。

比较前缀中的字母频率。

如果满意,请打印并增加计数。

在末尾打印计数。

示例

# defining a function for multiple calles def prefixes(string, _1, _2): # count count = 0 #空字符串进行比较 prefix = "" # iterating over the string for i in range(len(string)): #从字符串获取前缀 prefix = string[:i + 1] #比较前缀中的字母数 if prefix.count(_1) > prefix.count(_2): #如果成功,则打印前缀 print(prefix) # incrementing the count by 1 count += 1 #打印计数 print(f"Total prefixes matched: {count}") if __name__ == __main__: # 调用该函数 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