# Python code for run length encoding
from collections import OrderedDict
def runLengthEncoding(input):
# Generate ordered dictionary of all lower
# case alphabets, its output will be
# dict = {'w':0, 'a':0, 'd':0, 'e':0, 'x':0}
dict=OrderedDict.fromkeys(input, 0)
# Now iterate through input string to calculate
# frequency of each character, its output will be
# dict = {'w':4,'a':3,'d':1,'e':1,'x':6}
for ch in input:
dict[ch] += 1
# now iterate through dictionary to make
# output string from (key,value) pairs
output = ''
for key,value in dict.items():
output = output + key + str(value)
return output
# Driver function
if __name__ == "__main__":
input="wwwwaaadexxxxxx"
print (runLengthEncoding(input))
使用
string.count()
语法如下:
substring
是您试图查找的字母,[start_index]
是开始搜索的字母(请记住,python在使用索引时从0开始),而[end_index]
是停止搜索的字母正如其他人提到的,您可以使用str.count()。一种简单的方法是看第一个字母,数一数,然后从字符串中删除它的所有实例并重复。简单的递归答案可能如下所示:
您需要输入一个运行长度编码算法
Geeksforgeks在这方面有一篇很棒的文章:
https://www.geeksforgeeks.org/run-length-encoding-python/
输出:
你的例子是:
输出:
这正是你想要的
以上代码来自Geeksforgeks链接
相关问题 更多 >
编程相关推荐