python - How do I take an input string and count the number of characters in it by maintaining the order? -


my_string = "aaabbcccaa" required_output = "a3b2c3a2" 

please not provide code, try myself, please suggest me approach can required output.

as suggested @ggradnig i've tried below code.

 def count_string(s):     current_char= s[0]     counter =0     result_string = ''     in range(len(s)):         if s[i] == current_char:             counter+=1           if s[i] != current_char:             result_string=result_string+current_char+str(counter)             current_char = s[i]             counter = 1             continue     result_string=result_string+current_char+str(counter)          return result_string  given_string=count_string("aabbbccccaa") print(given_string) 

please suggest changes improve above code

use hashing.. dictionaries in python. make character key , occurrence value.. , traverse dictionary... , took empty string , append both key , value string.

edit

now think change approach instead of using sets under dictionary , making things complex can use simple approach. program working.

string2="" string=input() i=0 while(i<len(string)):     count=1     j in range(i+1,len(string)):         if string[i]==string[j]:             count+=1         else:             break     string2=string2+string[i]     string2=string2+str(count)     i=i+count print(string2) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -