Search code examples
pythonpython-2.7recursiondigits

Writing a recursive function that returns the digit with longest consecutive sequence


How do I write a recursive function that that takes an int value and returns the digit with the longest consecutive sequence?

For example, f(1122333) returns 3 and f(1223) returns 2

I have no idea how to approach this problem, and I'm kind of new to recursion in general.


Solution

  • Something like this. Not tested. Was fun to think about though.

    Pseudo code:

    (Assumes integer division)

    Def number helperLongest(number myNum): 
        Return longest(myNum, -1, 0, -1, 0)
    
    Def number longest(number myNum,number prevLongest, number numOfPrevLong, number currentLongest,number numOfLongest):
        If (myNum/10 < 1) //base case
            If (myNum == currentLongest)
                numOfLongest++
            Else //deal with corner case of < 10 input
                If (numOfLongest > numOfPrevLong)
                    prevLongest = currentLongest
                    numOfPrevLongest = numOfLongest
                currentLongest = myNum
                numOfLongest = 1
            return (numOfLongest>numOfPrevLong)?currentLongest:prevLongest
        Else //recurse
            if(myNum%10 == currentLongest) 
                numOfLongest++;
            Else //have to break the chain 
                 if (numOfLongest > numOfPrevLongest)
                     prevLongest = currentLongest
                     numOfPrevLongest = numOfLongest
                 currentLongest = myNum%10
                 numOfLongest = 1
            myNewNum = myNum/10;
            return longest(myNewNum,prevLongest,numOfPrevLong,currentLongest,numberOfLongest);
    

    In words: go through the number digit by digit, starting from the end. If the current last digit matches the one before it, increment the counter. If it doesn't, and it's bigger than the previous maximum, save it. Reset the current digit to the current last digit and reset the counter. Chop off the last digit. Feed the smaller number and all of this information back into the function until you get down to one final digit (the first digit in the original number). Compare your current counter with the maximum stored, and return the larger.

    One note: in case of a tie the first substring of matching numbers (which is actually the last substring in the original number) would be returned. If the other behavior is desired, then interchange the two > with >=.