1
line=input()
#taking a sentence

d1=1
#count variable

ln=len(line)
for i in range(0,ln):

    if line[i]==line[i+1]:

        d1+=1
    else:

        print(line[i],d1)
        d1=1

**sample test cases1

  • aaabcaaaa
  • sample output1 a 3 b 1 c 1 a 4

**

**my wrong output

  • aaabcaaaa
  • sample output1 a 3 b 1 c 1

** in my output, I'm not getting the last frequency of the last character

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91

3 Answers3

0

You only print the number if the next char is different. but the last char has no next char. change your if statement to:

if i != ln - 1 and line[i] == line[i + 1]:
Creepsy
  • 321
  • 3
  • 13
0

You need to add one last statement at the end, because it no longer goes into the else statement to print out the last letter frequency

Try


d1=1
#count variable

ln=len(line)
for i in range(0,ln-1):
    if line[i]==line[i+1]:

        d1+=1
    else:
        print(line[i],d1)
        d1=1

if d1 > 1:
    print(line[i],d1)
dsanatomy
  • 533
  • 4
  • 14
0
enter code here
line=input()
d1=1
ln=len(line)
output=""
for i in range(0,ln-1):
    if line[i]==line[i+1] and i!=ln-1:
        d1+=1

    else:
        output+=line[i]+str(d1)
        d1=1

output+=line[i+1]+str(d1)#this extra line solves my question#
print(output)

**Thanks to both of you for your respons **