Files
  • main.py
main.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
original = input("\nText to compress: ")
# the last character processed
last_char = original[0]
# the compressed version of the string
compressed = ""
# the number of occurrences of the current character
char_count = 0
for char in original:
  # if the character is the same as the previous one...
  if char == last_char:
    # increment the counter
    char_count += 1
  else:
    # ...otherwise add the number of times the previous character appeared
    compressed += str(char_count) + last_char
    char_count = 1
  # remember this character
  last_char = char
# add on the last character
compressed += str(char_count) + last_char
# print the compressed version
print("\nCompressed text:",compressed)
# calculate the percentage saving
saving = str(100 - int((len(compressed)/len(original))*100)) + "%."
# say how much shorted the compressed version is
print("\nThe uncompressed string is",str(len(original)),"characters long and the compressed version is",str(len(compressed)),"characters long - that's a reduction of",saving)