Python 中的遊程長度編碼


在本教程中,我們將學習如何在 Python 中建立遊程長度編碼。給定一個字串,返回一個包含字元和頻率的新字串。

例如,字串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

結論

如果你對教程有任何疑問,請在評論部分提出。

更新於:2020 年 2 月 12 日

2K+ 瀏覽量

職業生涯開啟篇章

完成課程獲得認證

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