Home > Mobile >  Can someone guide me with correct way to iterate in the following code
Can someone guide me with correct way to iterate in the following code

Time:11-19

This is a question from Python Challenge: Double letters

The goal of this challenge is to analyze a string to check if it contains two of the same letter in a row. For example, the string "hello" has l twice in a row, while the string "nono" does not have two identical letters in a row.

Define a function named double_letters that takes a single parameter. The parameter is a string. Your function must return True if there are two identical letters in a row in the string, and False otherwise.

I tried below code:

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

double_letters('hello')

CodePudding user response:

I was using a wrong range for the 'for loop'. Since, my if statement uses index 1, so my code was throwing an error as out of range.. Below is the correct code:

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

CodePudding user response:

A very basic solution for this:

def double_letters(word: str):
    prev_letter = None
    for letter in list(word):
        if prev_letter is None:
            prev_letter = letter
            continue
        if letter == prev_letter:
            return True
        prev_letter = letter
    return False
  • Related