简体   繁体   English

有人可以用正确的方法指导我在以下代码中进行迭代吗

[英]Can someone guide me with correct way to iterate in the following code

This is a question from Python Challenge: Double letters这是来自 Python 挑战的问题:双字母

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.例如,字符串“hello”连续两次有 l,而字符串“nono”没有连续两个相同的字母。

Define a function named double_letters that takes a single parameter.定义一个名为 double_letters 的 function,它采用单个参数。 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.如果字符串中有两个相同的字母,您的 function 必须返回 True,否则返回 False。

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')

The problem here is: when i return false at the end of my function, it works perfectly fine for a true statement (eg 'Hello'), but doesn't work for False statement (eg 'Master'), i get an error instead: IndexError: string index out of range这里的问题是:当我在 function 的末尾返回 false 时,它适用于 true 语句(例如“Hello”),但不适用于 False 语句(例如“Master”),我得到一个错误相反:IndexError:字符串索引超出范围

I was using a wrong range for the 'for loop'.我为“for循环”使用了错误的范围。 Since, my if statement uses index+1, so my code was throwing an error as out of range.. Below is the correct code:因为,我的 if 语句使用 index+1,所以我的代码抛出了超出范围的错误。下面是正确的代码:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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