简体   繁体   中英

checking string for double letter in a row

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

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"))
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]

Why not use regex ?

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

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:]))

You could also use reduce:

from functools import reduce

def double_letters(string):
    return bool(reduce(lambda x, y: not(x is y) and x and y, string))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM