Problem:
Given a string aaabbcccaad
print the no. of occurrence of the character in the same order in which the character occurred.
Expected output:
(a, 3), (b, 2), (c, 3), (a, 2), (d, 1)
The approach:
- Loop through each character.
- When the next character is not same as the current character, record the next character and its position.
- count of occurence = Iterate the
pos_list
(position list ), take the difference - Return character and its count in in the same order
Solution:
def seq_count(word):
wlen = len(word)
pos = 0
pos_list=[pos]
alph = [word[0]]
result = []
for i in range(wlen):
np = i+1
if np < wlen:
if word[i] != word[i+1]:
pos = i+1
pos_list.append(pos)
alph.append(word[i+1])
pos_list.append(wlen)
for i in range(len(pos_list)-1):
result.append((alph[i], pos_list[i+1] - pos_list[i]))
return result
print seq_count("aaabbcccaad")
Note:
I know this may not be the conventional solution, i was finding difficult to count the character and maintain its count as we iterate through the string, since I'm a beginner in python. Pls let me know how can i do it better.