Home > Software engineering >  how to count pairs when all are the same
how to count pairs when all are the same

Time:11-08

I asked this question and got a response that worked correctly. But I need it to be written in a for loop. What I have right now works for each assertion except for the last two. For mmm it returns 1 pair but it should return 2. for the first two and the second and last. Is there anything i can add to what i have right now to account for this.

def charPairs(word):
    count = 0
    wordchars = set(word)
    for char in wordchars:
        count  = word.count(char   char)
    return count


# Tests
assert (charPairs("") == 0)
assert (charPairs("H") == 0)
assert (charPairs("abc") == 0)
assert (charPairs("aaba") == 1)
assert (charPairs("aabb") == 2)
assert (charPairs("mmm") == 2)
assert (charPairs("aabbccc") == 4)

CodePudding user response:

Try this:

def charPairs(word):
    count = 0
    for i in range(len(word) - 1):
        if word[i] == word[i 1]:
            count  = 1
    return count
  • Related