-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRun-Length Encoding.py
42 lines (40 loc) · 1.15 KB
/
Run-Length Encoding.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def decode(string):
store_num = ""
result = ""
for char in string:
if char.isalpha():
if store_num == "":
result += char
continue
result += char * int(store_num)
store_num = ""
continue
if char.isnumeric():
store_num += char
continue
if store_num == "":
result += char
continue
result += char * int(store_num)
store_num = ""
return result
def encode(string):
if string == "":
return string
previous_char = string[0]
number_of_appearances = 0
result = ""
for char in string:
if char != previous_char:
if number_of_appearances == 1:
result += previous_char
previous_char = char
continue
result += str(number_of_appearances) + previous_char
number_of_appearances = 1
previous_char = char
continue
number_of_appearances += 1
if number_of_appearances == 1:
return result + char
return result + str(number_of_appearances) + char