使用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

結論

如果您在理解程式碼方面遇到任何問題,請在評論區提出。

更新於:2020年2月12日

瀏覽量:550

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.