Everything else seems to work just fine, but last character is always off by 1. For example, if I input abcccddd, I get a1b1c3d2 but I should get a1b1c3d3. Any hint would be much appreciated!
Prompt: String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z). Do the easy thing first. Compress the string, then compare the lengths. Be careful that you aren't repeatedly concatenating strings together, this can be very inefficient.
def compression(string):
hash = {}
list = []
count = 0
for i in range(len(string) - 1):
if string[i - 1] != string[i] or i == 0:
if string[i] != string[i + 1] or i == len(string) - 2:
count = count + 1
list.append(str(string[i]))
list.append(str(count))
count = 0
elif string[i] == string[i + 1]:
count = count + 1
elif string[i - 1] == string[i]:
if string[i] != string[i + 1] or i == len(string) - 2:
count = count + 1
list.append(str(string[i]))
list.append(str(count))
count = 0
if string[i] == string[i + 1]:
count = count + 1
print(list)
result = "".join(list)
if len(result) == len(string):
return string
else:
return result
string = "abcccfffgggg"
compression(string)
hashfor?-1is used as an index for the string?