I have a basic code question for Python 3.

Asked 2 years ago, Updated 2 years ago, 17 views

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

2022-09-22 20:01

2 Answers

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.


2022-09-22 20:01

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)]


2022-09-22 20:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.