+ 1
I had to make a condition that the input sequence ends in a character (0) so that the program knows when to end. Avoidable?
8 Answers
+ 3
You can do len(input) and do it without 0.
Of course it is needed to rebuild this sample of code.
+ 2
The nested while is not working well. It want to have access to not existing element of string. You have to check length == 0 first (before getting to index of array).
The if/while statements works from left to right: on the first statement it causes error and not check second. If you change them then it first check the length and later try check the index of array.
+ 2
thanks
+ 2
By the way try to code:
a != b
Instead of
not a == b
+ 2
thanks a lot!
I got it working!
+ 1
How it works: aaabbc0 becomes a3b2c
+ 1
input = input() #input any sequence of letters
length = len(input) #initialize length
print(length)
adress = 0 #intialize adress
compressed = str() #intialize compressed
while not length == 0: #end loop when 0
letter = input[adress] #letter to check if it repeats
compressed += input[adress] #add letter to output
nletters = 0 #reset number of consecutive letters
while input[adress] == letter: #loop for each consecutive letter
adress += 1 #increment character of string read
nletters += 1 #increment number of consecutive letters
length -= 1 #decrement length
print(length)
if not nletters == 1: #skip add number of consecutive letters if only one letter
nletters = str(nletters)
compressed += nletters #add number of consecutive letters to output
print(compressed) #print output
+ 1
thanks! ok so why isn't this working?