-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01 Run-length code.py
45 lines (40 loc) · 1.41 KB
/
01 Run-length code.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
43
44
45
def main():
# Get input
task = input('Enter a sentence for Encoding (E) or Decoding (D): ')
text = task[2::] # Create a string with only the sentence to encode/decode
# Check for Encoding/Decoding mode
if task[0] == 'E':
encode(text)
else:
decode(text)
def encode(text):
# Count the repetition of items in text and return a string of letter-number pairs
result = ''
for i in range(len(text)):
item = text[i]
if result:
if result[-1] != item: # item is different from previous item
result += str(count_rep) # add count_rep of previous item to string result
count_rep = 1
result += item
if i == len(text) -1:
result += str(count_rep)
else: # item is repeated
count_rep += 1
if i == len(text) -1:
result += str(count_rep)
else: # this is the first item in text
count_rep = 1
result += item
if i == len(text) -1:
result += str(count_rep)
print(result)
def decode(text):
result = ''
# Grab letter-number pairs from text
# and return n times of the letter with n being its paired number
for i in range(1, len(text), 2):
result += int(text[i]) * text[i-1]
print(result)
if __name__ == '__main__':
main()