How would I count consecutive characters in Python to see the number of times each unique digit repeats before the next unique digit?
At first, I thought I could do something like:
JavaScript
x
13
13
1
word = '1000'
2
3
counter = 0
4
print range(len(word))
5
6
for i in range(len(word) - 1):
7
while word[i] == word[i + 1]:
8
counter += 1
9
print counter * "0"
10
else:
11
counter = 1
12
print counter * "1"
13
So that in this manner I could see the number of times each unique digit repeats. But this, of course, falls out of range when i
reaches the last value.
In the example above, I would want Python to tell me that 1 repeats 1, and that 0 repeats 3 times. The code above fails, however, because of my while
statement.
How could I do this with just built-in functions?
Advertisement
Answer
A solution “that way”, with only basic statements:
JavaScript
1
16
16
1
word="100011010" #word = "1"
2
count=1
3
length=""
4
if len(word)>1:
5
for i in range(1,len(word)):
6
if word[i-1]==word[i]:
7
count+=1
8
else :
9
length += word[i-1]+" repeats "+str(count)+", "
10
count=1
11
length += ("and "+word[i]+" repeats "+str(count))
12
else:
13
i=0
14
length += ("and "+word[i]+" repeats "+str(count))
15
print (length)
16
Output :
JavaScript
1
3
1
'1 repeats 1, 0 repeats 3, 1 repeats 2, 0 repeats 1, 1 repeats 1, and 0 repeats 1'
2
#'1 repeats 1'
3