Python Forum
Codility Binary Gap Exercise
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Codility Binary Gap Exercise
#1
Heya, rookie coder here trying to build up my know-how.
I've been working on this problem for far too long and was hoping I could get some insight here.
The current problem I'm facing is getting the program to invalidate series of zeros that don't end in a one, everything else seems to work as intended, albeit with delightfully sloppy novice code.
num = int(input('enter a number:'))
binlst = list()
streak = 0
while int(num) > 0 :
    if num > 2147483647 :
        print('integer too big')
        break
    bin = num % 2
    binlst.insert(0,bin)
    num = int(num / 2)
while len(binlst) < 8 :
    binlst.insert(0,0)
startone = None
dic = dict()
zeros = 0
for digit in binlst :
    if digit == 1 :
        dic = dict()
        startone = 0
    if digit == 0 and dic.get(zeros,0) == 0 :
        dic[zeros] = 1
    elif digit in dic :
        dic[zeros] = dic[zeros] + 1
    if dic.get(zeros,0) > 0 and dic.get(zeros,0) > streak and startone is not None :
        streak = dic.get(zeros,0)
print(binlst)
print('Longest streak of zeros:',streak)
Sample inputs and outputs:
In: 15, Out: 00001111 with streak 0 Cool
In: 42, Out: 00101010 with streak 1 Cool
In: 25, Out: 00011001 with streak 2 Cool
In: 32, Out: 00100000 with streak 5 Wall

Would love to hear some guidance on this,
Thanks!
Reply


Messages In This Thread
Codility Binary Gap Exercise - by Westerner - Jan-08-2021, 09:51 AM
RE: Codility Binary Gap Exercise - by deanhystad - Jan-08-2021, 03:59 PM
RE: Codility Binary Gap Exercise - by Westerner - Jan-08-2021, 09:20 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Codility Frog River One Westerner 2 2,477 Jan-09-2021, 06:35 PM
Last Post: deanhystad
  hex file to binary or pcap to binary baran01 1 5,792 Dec-11-2019, 10:19 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020