I am a beginner studying Python 3.
I have to write a code that outputs the value a3b2c6a1 from the string 'aaabbccccca', but I can't understand the answer, so I'm posting a question.
def compress_string(s):
_c=''
cnt=0
result=''
for c in s:
if c!=_c:
_c=c
if cnt: result += str(cnt)
result += c
cnt = 1
else:
cnt += 1
if cnt: result += str(cnt)
return result
print(compress_string('aaabbcccccca'))
I'd like to ask you to solve the first a and the second a.
python
Traverses the entire string in Chinese characters.
Make sure that one character is the same as the one you checked before.
Otherwise, the same string is finished, so result + the number counted when it is the same and stored in the form a3.
If equal, only count +1.
This may be irrelevant to the question, but upload an example implemented in a different way.
import itertools
s = 'aaabbccccca'
groups = itertools.groupby(s)
print([(c, len(list(group))) for c, group in groups])
# You can also do it like map (lambda group: (group[0], len (list(group[1]))), groups).
[('a', 3), ('b', 2), ('c', 5), ('a', 1)]
© 2024 OneMinuteCode. All rights reserved.