Home > database >  checking string for double letter in a row
checking string for double letter in a row

Time:11-09

I'am trying to create a funtion that returns True if a string has the same letters side by side

Expected Output:
print(double_letters("Error")) should return True because of rr.

def double_letters(string):
    
    string_len = len(string) - 1 
    index1 = 0  
    index2 = 1  
    word1 = string[index1, string_len]
    word2 = string[index2, string_len]

    while string_len > 0:
        if word1 != word2:
            index1  = 1
            index2  = 1         #keeps the checked words side by side
            string_len -= 1    
        else:
            return True

CodePudding user response:

You can easily compare two consecutive letters in a word using indexes

def double_letters(word):
    for i in range (len(word)-1):
        if word[i] == word[i 1]:
            return True
    return False

print(double_letters("Error"))

CodePudding user response:

if word1 != word2:

Here you are always comparing the words, and the words are not being updated in your loop. You should compare the characters at index1 and index2. Namely word1[index1] and word2[index2]

CodePudding user response:

Why not use regex ?

m = re.search(r"(.)\1{1,}", 'error')
m.group(0)

CodePudding user response:

You can do this with sets by intersecting the list of character,position pairs with the list of character,position 1 pairs. These pairs can be obtained using the enumerate() funciton:

def doubles(S):
    return any(set(enumerate(S))&set(enumerate(S,1)))

print(doubles("akdgjg"))     # False
print(doubles("dkjhfkddhk")) # True

A more efficient way would be to use zip() to access each letter with its successor and compare them together:

def doubles(S):
    return any(a==b for a,b in zip(S,S[1:]))

CodePudding user response:

You could also use reduce:

from functools import reduce

def double_letters(string):
    return bool(reduce(lambda x, y: False if x == y else isinstance(x, str) and y, string))
  • Related