0

Input string = "wwwwwwwwwkkktttttrrrrwww" expected output = "9w3k5t4r3w"

I just want to know if there a more efficient/better way to achieve this please?

def my_encode(str1):
    temp = str1[0]
    cnt = 0
    final = ''
    for letter in str1:
        if letter == temp:
            cnt += 1
        else:
            final = final + str(cnt) + temp
            cnt = 1
            temp = letter
    final = final + str(cnt) + temp
    return final


print(my_encode('wwwwwwwwwkkktttttrrrrwww'))
1
  • That looks reasonably straightforward, and understandable; I wouldn't bother changing it unless you've actually measured it to be a bottleneck in your program. One option if you did need to speed it up: use a regular expression to directly split your string into runs of the same character. re.sub(r"(.)\1*", lambda m: str(len(m.group(0))) + m.group(1), 'wwwwwwwwwkkktttttrrrrwww') Commented Jul 10, 2020 at 18:43

1 Answer 1

1

Perhaps itertools.groupby will work for you

key = 'wwwwwwwwwkkktttttrrrrwww'
from itertools import groupby
print(''.join('{}{}'.format(len(list(k)), g) for g, k in groupby(key)))
>>> 9w3k5t4r3w
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.