The problem with your code is that it counts all occurrences of a given letter in the string, regardless of its position (the value returned by the method count
) - and does not take into account separate blocks with the same letter.
For the record, this algorithm is called a "run length encoding" (RLE), and is a compression algorithm still used in many basic file types that we use on a day-to-day basis (e.g., GIF images, and Postscript images).
Good - the solution is to use more state variables - to go through the letter of the original string, to be able to look "backwards" and see which is the last letter - and take an action if it is equal to the current, and another case is different.
Another thing to keep in mind is that in Python, strings are immutable objects. So, although in this case, the performance is not relevant (anyway this code will run in less than 10ms for strings smaller than 30 pages of text), it is better that the mutable code data is built in a "mutable" structureas a list, and after everything is collected, "frozen" in an output string. For this "freeze" the key is the ". Join" method of the strings, which use a list as input.
Your job can stay that way:
def rle(input_str):
count = -1
previous = None
result = []
for char in input_str:
count += 1
if char != previous and previous != None:
result.append((count, previous))
count = 0
previous = char
if previous:
result.append((count + 1, previous))
output = ''.join((str(pair[0]) + pair[1]) for pair in result)
return output
Your answer is basically correct - but with a "no Pythonico" accent (getting to the point of having code that is simply not Python and will not fucnionar as you wanted -
str(++quantidade)
does not add "1" in "quantity" - it is not a syntax error because it twice applies the "positive number" operator+
variable, but its value does not change). But principalmnte in Python is not usedfor
by indices, except when really necessary - since thefor
natural language is a "for each" that already provides the data sequence element directly.– jsbueno
Opa, my intuition was to make the code really very explicit and with a syntax that can be applied in other languages, because it seems to be the case of someone who is starting to program, so the comments etc, thanks! :)
– Daniel Mendes
I’m starting, you got it! Your explanation was super didactic, the little problems in the syntax that can cause mistakes are easy to change. Thank you so much for your help! :)
– Diovana Valim