Python程式:遞迴查詢給定字母在字串中出現的次數


當需要使用遞迴檢查給定字母在字串中出現的次數時,可以定義一個方法並使用“if”條件。

遞迴計算更大問題的小部分輸出,並將這些部分組合起來以給出更大問題的解決方案。

示例

以下是演示 -

 線上演示

def check_frequency(my_str,my_ch):
   if not my_str:
      return 0
   elif my_str[0]==my_ch:
      return 1+check_frequency(my_str[1:],my_ch)
   else:
      return check_frequency(my_str[1:],my_ch)
my_string = input("Enter the string :")
my_char = input("Enter the character that needs to be checked :")
print("The frequency of " + str(my_char) + " is :")
print(check_frequency(my_string,my_char))

輸出

Enter the string :jaanea
Enter the character that needs to be checked :a
The frequency of a is :
3

解釋

  • 定義了一個名為“check_frequency”的方法,該方法接受字串和字元作為引數。
  • 它檢查字串中的字元是否與傳遞給方法的字元匹配。
  • 如果匹配,則返回。
  • 否則,對字串的所有字元遞迴呼叫該方法。
  • 字串和字元作為使用者輸入獲取。
  • 透過將這些值作為引數傳遞來呼叫該方法。
  • 輸出顯示在控制檯上。

更新於: 2021年3月12日

660 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.