1

Let's say I have a string presented in the following fashion:

st = 'abbbccccaaaAAbccc' 

The task is to encode it so that single characters are followed by a number of their occurences:

st = 'a1b3c4a3A2b1c3'

I know one possible solution but it's too bulky and primitive.

s = str(input())
l = len(s)-1
c = 1
t = ''
if len(s)==1:
    t = t +s+str(c)
else:
    for i in range(0,l):
        if s[i]==s[i+1]:
            c +=1
        elif s[i]!=s[i+1]:
            t = t + s[i]+str(c)
            c = 1
        for j in range(l,l+1):
            if s[-1]==s[-2]:
            t = t +s[j]+str(c)
        elif s[-1]!=s[-2]:
            t = t +s[j]+str(c)
            c = 1
print(t)

Is there any way to solve this shortly and elegantly?

P.S: I'm an unexperienced Python user and a new StackOverflow member, so I beg my pardon if the question is asked incorrectly.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
Ramiil
  • 59
  • 8

2 Answers2

3

Take advantage of the standard library:

from itertools import groupby

st = "abbbccccaaaAAbccc"

print("".join("{}{}".format(key, len(list(group))) for key, group in groupby(st)))

Output:

a1b3c4a3A2b1c3
>>> 
Paul M.
  • 10,481
  • 2
  • 9
  • 15
0

just loop through and count. There are more graceful snippets but this will get the job done and is clear:

count = 1
char = st[0]
new_st = []
for c in st[1:]:
    if c == char:
        count += 1
    else:
      new_st.append(char + str(count))
      char = c
      count = 1
new_st.append(char + str(count))
s2= "".join(new_st)

print(s2)  # 'a1b3c4a3A2b1c3'

If you want a fancy recursive solution:

def compose(s):
    if not s:
        return ""

    count = 1
    for char in s[1:]:
        if s[0] != char:
            break
        count += 1
    return s[0] + str(count) + compose(s[count:])
anon01
  • 10,618
  • 8
  • 35
  • 58