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

Python에서 길이 인코딩 실행

<시간/>

이 자습서에서는 Python에서 실행 길이 인코딩을 만드는 방법을 배웁니다. 주어진 문자열은 char 및 frequency.를 포함하는 새 문자열을 반환합니다.

예를 들어, 문자열 tutorialspoint t3u1o2r1i2a1l1s1p1n1로 인코딩됩니다. . 순서는 모든 문자+빈도입니다. . 모두 합류하고 돌아갑니다. 프로그램을 작성하려면 아래 단계를 참조하십시오.

  • run_length_encoding이라는 이름으로 함수를 작성하십시오.

  • OrderedDict로 사전 초기화 초기 문자 수를 0으로 가져옵니다.

  • 문자열의 모든 문자를 반복하고 사전에서 카운트를 증가시킵니다.

  • 모든 문자와 해당 빈도를 결합하십시오. 그리고 그것을 인쇄하십시오.

  • 문자열을 초기화하고 함수를 호출합니다.

위 텍스트의 코드를 보자.

# importing the collections
import collections
# function
def run_length_encoding(string):
   # initialzing the count dict
   count_dict = collections.OrderedDict.fromkeys(string, 0)
   # iterating over the string
   for char in string:
      # incrementing the frequency
      count_dict[char] += 1
   # initializing the empty encoded string
   encoded_string = ""
   # joining all the chars and their frequencies
   for key, value in count_dict.items():
      # joining
      encoded_string += key + str(value)
      # printing the encoded string
print(encoded_string)
# initializing the strings
string = "tutorialspoint"
# invoking the function
run_length_encoding(string)
# another string
string = "aaaaaabbbbbccccccczzzzzz"
run_length_encoding(string)

출력

위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

t3u1o2r1i2a1l1s1p1n1
a6b5c7z6

결론

튜토리얼에서 의문점이 있으면 댓글 섹션에 언급하세요.