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"))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With