Reputation: 23
1) The purpose of the code: I have coded an algorithm, which is supposed to give me the exact number, which is the most frequent and consecutive at the same time number.
2) What I have tried: I have tried to write the whole code, and actually managed to get that exact number. I have also added the frequency of that number, which is the output.
3) What I need: I am looking for the algorithm, which will identify the first starting index of those consecutive numbers. For example, if the input is 123777321, as an index number 3 is needed, the reason being 777 is the most frequent consecutive number in this input, it should find its "index", and also print it out.
The Code I have written:
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)
Example of an input: Please enter a string: 123777321
Example of an output: Longest same number sequence is of number 7 by being repeated 3 times in a row, with the first index starting at 3
Upvotes: 0
Views: 232
Reputation: 1447
Just add a variable to track the starting index of the best sequence.
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)
Upvotes: 1
Reputation: 14238
From your comments, I assume you are trying to get the index at which the most frequently occurring element starts right?
Declare another variable like max_index
and update it each time you update count
and use that to print the index.
.....
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))
......
Upvotes: 0