【问题标题】:Starting Index of the Most Frequent Consecutive Number Algorithm最频繁连续数算法的起始索引
【发布时间】:2020-03-02 14:44:53
【问题描述】:

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

开始

【问题讨论】:

  • 你的问题是什么?
  • 代码,在这种情况下将获取 7 的第一个/起始索引,因为它是最频繁和连续的数字。
  • 您的实际代码不起作用?
  • 可以,但不返回索引值。
  • 您的算法在 O(N^2) 时间内运行效率极低

标签: python algorithm frequency


【解决方案1】:

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

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)

【讨论】:

  • 这正是我所需要的!谢谢,提前,感谢它!
【解决方案2】:

从您的 cmets 中,我假设您正在尝试获取最常出现的元素开始的索引,对吗? 声明另一个变量,如 max_index,并在每次更新 count 时更新它,并使用它来打印索引。

.....
max_index = 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]
            max_index = 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, max_index))
......

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 2015-11-05
    • 2015-08-14
    • 2021-11-10
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多