Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a repeated character in a string and determining how many times in a row it is repeated in python

I have a text file with a single line in it. The line of text is a whole bunch of random numbers. I need to determine the most amount of times a 5 is repeated and print how many times it's repeated. For example: numList: 1234555325146555. The most amount of times 5 is repeated in a row is 3 and that happens 2 times. Here is the code I have so far, it shows me at what positions 5 occurs. I think this is the first step but can't figure out how to move on.

numbers = open("numbers.txt",'rU')
count = -1
numString = numbers.readline()
for num in numString:
    count += 1
    if num == '5':
        print count
        counter += 1
like image 323
user1294377 Avatar asked Dec 27 '22 21:12

user1294377


1 Answers

You got the right idea for finding out which position the 5 is in.

So how do you find out how long a row of 5's is? Think about:

  1. You need to know if you've found a 5, if its part of a series. Keep track of the previous number. If that's also a 5, then you're continuing a series.
  2. If you're continuing a series, then have another counter to keep track how long it is.
  3. You need to reset the counter if you reach a number that is not a 5. But before resetting, you need to store that value.
  4. For the next part of the problem (finding out how many series of 5's there are), try using additional "meta" variables that keeps track of the longest series you have so far and how many times you've seen that.

Good luck! and keep on asking questions

like image 117
applepie Avatar answered Apr 11 '23 13:04

applepie