在列表中查找连续的字母

时间:2014-09-13 22:45:58

标签: python algorithm numbers

我有以下顺序:'TATAAAAAAATGACA'我希望Python打印出包含最多连续重复的字母...在这种情况下将是7 'A' s。如果仅使用foriflenrange和计数变量,您将如何做到这一点?

1 个答案:

答案 0 :(得分:1)

def consecutiveLetters(word):
    currentMaxCount = 1
    maxChar = ''
    tempCount = 1

    for i in range(0, len(word) - 2):
        if(word[i] == word[i+1]):
            tempCount += 1
            if tempCount > currentMaxCount:
                currentMaxCount = tempCount
                maxChar = word[i]
        else:
            currentMaxCount = 1

    return [maxChar,tempCount]

result = consecutiveLetters("TATAAAAAAATGACA")

print("The max consecutive letter is ", result[0] , " that appears ", result[1], " times.")

这将打印:The max consecutive letter is A that appears 7 times.