Binary gap length ( Python exercise )

Sometimes I like to mess around http://www.codility.com , doing the excercises trying to keeping my development skills fresh. This is my take on the binary gap length problem using basic Python 3. The binary gap length is an excercise where you need to come up with a code, returning the longest sequence of zeros in a 16 digit “binary” string. This question also often shows up at developer job interviews.

#get max binary zeros gap
import re
import sys


def get_binary_gap(input_seq):
    iterator_zeros = '0'
    output = None
    while len(iterator_zeros) < 16:
        if iterator_zeros in input_seq:
            stack = len(iterator_zeros)
            if stack >= len(iterator_zeros):
                output = stack
        elif iterator_zeros not in input_seq and len(iterator_zeros) == 1:
            output = 0
        else:
            pass
        iterator_zeros = iterator_zeros + '0'
    return output


def main(arg):
    input_seq = arg
    if len(input_seq) == 16 and bool(re.match("^[0-1]{1,16}$", input_seq)):
        output = get_binary_gap(input_seq)
        print(f'The max binary gap of zeros in sequence {input_seq} is {output}')
    else:
        print(f'invalid input sequence {input_seq}')


if __name__ == '__main__':
    arg = str(sys.argv[1])
    main(arg)

Execute with the binary sequence argument like for instance :

python.exe C:/codility/binary_gap/__main__.py 0100000101010100
Advertisements