Adjacent letters in lines

Trying to write a program that will count the number of matching letter pairs adjacent to each other ("mississippi" contains 3) and displays this number.

Not sure what I'm doing wrong, but I have to use strings, while loop and variables as part of the code. It seems to work for the first line and prints 3, and then displays the IndexError: string index out of range for the second string example.

def count_pairs(s):
    index = 0
    pairs = 0
    letter = 0
    nextletter = 0
    while index < len(s):
        letter = s[index]
        index = index + 1
        nextletter = s[index]
        if letter == nextletter:
            pairs = pairs + 1
            index = index + 1
        else:
            index = index + 1
    return pairs

print(count_pairs("ddogccatppig"))
print(count_pairs("dogcatpig"))
print(count_pairs("xxyyzz"))
print(count_pairs("a"))
+4
source share
2 answers

In a while loop, you gain access to s[index]both and to s[index + 1].

Then you should change:

while index < len(s):

in

while index + 1 < len(s):

or, equivalently:

while index < len(s) - 1:
+2
source

groupby.

>>> from itertools import groupby
>>> sum(len(tuple(g)) > 1 for k, g in groupby("ddogccatppig"))
3

, , for

>>> s = "ddogccatppig"
>>> sum(s[idx] == j for idx, j in enumerate(s, 1) if idx != len(s))
3

for, sum

+5

Source: https://habr.com/ru/post/1627378/


All Articles