Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python을 사용하여 가장 빈도가 높은 주어진 문자열의 모든 접두사 계산

<시간/>

이 튜토리얼에서는 두 번째 단어보다 알파벳의 빈도가 높은 단어를 세어 출력하는 프로그램을 작성할 것입니다.

문자열과 두 개의 알파벳을 가져옵니다. 첫 번째 알파벳의 빈도가 높은 접두사가 인쇄됩니다. 그리고 출력 끝에 카운트를 표시합니다.

몇 가지 예를 살펴보겠습니다.

입력

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
   # 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

결론

코드를 이해하는 데 문제가 있는 경우 댓글 섹션에 언급하세요.