python - 最频繁连续数算法的起始索引
问题描述
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开始
解决方案
只需添加一个变量来跟踪最佳序列的起始索引。
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)
推荐阅读
- java - How to define multiple query parameters in Spring boot
- c++ - 如何在 C++ 中的字符串函数中不返回任何值?
- vue.js - BootstrapVue 表粘性标题(CoreUI)
- git - 每当我尝试执行 git clone,git pull 时,Git 每次都会询问错误 URL 的密码
- spring - Spring Batch RabbitMQ 问题
- php - 如何对具有实时搜索功能的表进行分页?
- python-3.x - 使用带有方法的 python `eval()`
- c# - 使用递归创建一个程序,该程序将数组中的奇数作为特定格式的字符串返回 c#
- python - Python分割线并将其写入文件
- java - 从Java中的国家代码获取默认语言