Search code examples
pythonstringlistintegersequences

Best way of getting the longest sequence of even digits in an integer


What would be the most efficient way of getting the longest sequence of even digits in an integer in Python? For example, if I have a number 2456890048, the longest sequence should be 0048.

Should the integer be converted to a string to determine the longest sequence? Or should it be converted into the list and then, based on the indexes of each item, we would determine which sequence is the longest? Or is there a more efficient way that I am not aware of ( i am quite new to Python, and i am not sure what would be the best way to tackle this problem).


Solution

  • You can use itertools.groupby and max:

    >>> from itertools import groupby
    def solve(strs):
         return max((list(g) for k, g in groupby(strs, key=lambda x:int(x)%2) if not k),
                                                                                key=len)
    ... 
    >>> solve('2456890048') #or pass `str(2456890048)` if you've integers.
    ['0', '0', '4', '8']
    >>> solve('245688888890048')
    ['6', '8', '8', '8', '8', '8', '8']
    

    Here:

    [list(g) for k, g in groupby('2456890048', key=lambda x:int(x)%2) if not k]
    

    returns:

    [['2', '4'], ['6', '8'], ['0', '0', '4', '8']]
    

    Now we can apply max on this list(with key=len) to get the longest sequence. (Note that in the original code I am using a generator expression with max, so the list is not created in the memory.)