Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adjacent letters in strings

Tags:

python

string

Trying to write a program that will calculate the number of matching letter pairs adjacent to one another ("mississippi" contains 3) and output that number.

Not sure what I'm doing wrong, but I have to use strings, a while loop, and variables as parts of the code. It seems to work for the first line and outputs 3, then throws an 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"))
like image 234
xcascam Avatar asked Mar 14 '23 09:03

xcascam


1 Answers

You are reimplementing the functionality of groupby. Using library functions helps avoid bugs

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

Regardless, I think a for loop is more appropriate here

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

You can pull it out to a long handed for loop if you don't want to use sum

like image 159
John La Rooy Avatar answered Mar 27 '23 07:03

John La Rooy