Question

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).

Was it helpful?

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.)

OTHER TIPS

I think it is one of most efficient way

def longest(i):
    curMax = m = 0

    while i != 0:
        d = i % 10 % 2
        i = i / 10
        if d == 0:
            curMax += 1
        else:
            m = max(m, curMax)
            curMax = 0

    return max(m, curMax)

print longest(2456890048)

You can extract all runs of even numbers using a regexp, and find the longest using max.

import re

def longest_run(d):
    return max(re.findall('[02468]+', str(d)), key=len)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top