I have the following function which I used to find the length of the places in a binary number where zeros are encapsulated by ones:
def solution(N):
# write your code in Python 2.7
# convert to binary
binary = bin(N)[2:] # results prefixed with '0b'
# special case of no zeros
if '0' not in str(binary):
print('No binary gap in %s'% str(binary))
return 0
# special case of all zeros after first 1
if '1' not in str(binary)[1:]:
print('No binary gap in %s'% str(binary))
return 0
# special case of N == 1 = 01
if N == 1:
print('No binary gap in %s'% str(binary))
return 0
bgaps = []
sbin = str(binary)
print(sbin)
spbin = sbin.split('1')
print(spbin)
for i in spbin:
if i == '': continue
bgaps.append(len(i))
return max(bgaps)
for N in [6,328,147,15,2,483,647]:
print(solution(N)
The results show that string split doesn't always return a '' where the delimiter used to be. The happens e.g. for 101001000 where the split returns
['', '0', '00', '000']
instead of
['', '0','', '00', '', '000']
I suspect that this has to do with a special meaning of '01' but the delimiter is '1'. Any thoughts on why this split behaves this way?
splitthrows away the delimiter:"a,b,c".split(',') == ["a", "b", "c"].