首页 > 解决方案 > 最频繁连续数算法的起始索引

问题描述

1)代码的目的:我编写了一个算法,它应该给我确切的数字,这是同时出现的最频繁和连续的数字。

2)我尝试过的:我尝试编写整个代码,并且实际上设法获得了那个确切的数字。我还添加了该数字的频率,即输出。

3)我需要什么:我正在寻找算法,它将识别那些连续数字的第一个起始索引。比如输入123777321,因为需要索引号3,原因是777是这个输入中出现次数最多的连续数,应该找到它的“索引”,并打印出来。

我写的代码:

def maxRepeating(str):
    length = len(str)
    count = 0

    result = str[0]
    for i in range(length):

        current_count = 1
        for x in range(i + 1, length):

            if (str[i] != str[x]):
                break
            current_count += 1

        if current_count > count:
            count = current_count
            result = str[i]

    print("Longest same number sequence is of number {} by being repeated {} times in a row, with the first index starting at {}".format(result, count, i))



inputString = str(input("Please enter the string: "))

maxRepeating(inputString)

输入示例:请输入字符串:123777321

输出示例:最长的相同数列是数字 7,连续重复 3 次,第一个索引从 3开始

标签: pythonalgorithmfrequency

解决方案


只需添加一个变量来跟踪最佳序列的起始索引。

def maxRepeating(str):
    length = len(str)
    count = 0
    result = str[0]
    start_ind = None

    for i in range(length):

        current_count = 1
        for x in range(i + 1, length):

            if (str[i] != str[x]):
                break
            current_count += 1

        if current_count > count:
            count = current_count
            result = str[i]
            start_ind = i

    print("Longest same number sequence is of number {} by being repeated {} times in a row, with the first index starting at {}".format(result, count, start_ind))



inputString = str(input("Please enter the string: "))

maxRepeating(inputString)

推荐阅读