首页 > 解决方案 > 有没有办法识别一个单词是否有相同的字母相邻?

问题描述

我正在尝试在 python 中创建一个函数,它使用文本文档中的单词列表来执行特定的函数。所有其他功能都可以正常工作,因此 word 文档没有问题。我正在尝试创建的此功能通过 word 文档上的每个单词进行查看,并判断其中是否有两个相同的字母彼此相邻。它总是说文档中有0个字母接触。

我已经尝试过了,但我一生都无法理解为什么它不起作用,在

if word[a] == word[a+1:]:变量a为0,此时应该是单词的字母

def sameLettersTouchingFn(wordDocument):

    sameLettersTouchingCount = 0

    for word in wordDocument:

        for a in range(len(word)-1): #for every letter in the word

            if word[a] == word[a+1:]: #if letter is same as one next to it

                sameLettersTouchingCount +=1 # count goes plus one

        if sameLettersTouchingCount == 1: # if it has two letters touching

            print(word, "Has two of the same letter touching") #prints it has two letters touching


    print ("There is", sameLettersTouchingCount, "words with letters touching")

我的预期结果是打印带有相同字母的单词,并打印有多少单词有相同的字母。它没有说任何单词具有相同的字母感人,并说 0 个单词具有相同的字母感人

标签: pythonalgorithmfunction

解决方案


if word[a] == word[a+1:]:

应该

if word[a] == word[a+1]:

第一个是单词的其余部分而不是字母


推荐阅读