# run length compression algorithm def compress_s(s): if len(s) == 0: return None final_arr = [] index = 0 letter = s[0] for el in s: if el == letter and ord(el) == ord(letter): index += 1 else: final_arr.append(letter + repr(index)) letter = el index = 1 final_arr.append(letter + repr(index)) return "".join(final_arr) print(compress_s("AAAaaa")) #or -- similar solution with a while loop def compress2(s): r = "" l = len(s) #edge cases if l == 0: return "" if l == 1: return s + "1" count = 1 i = 1 while i < l: if s[i] == s[i-1]: count += 1 else: r = r + s[i-1] + str(count) count = 1 i += 1 r = r + s[i -1] + str(count) return r
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question