#๐ count set bits in succession
43 messages ยท Page 1 of 1 (latest)
@violet ice
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
would a lookup table work?
there are only 256 possible values for a byte so yes
but also, int.bit_count exists, and you can extract selected bits with &, so
(x & 0b1111).bit_count()```
gets the amount of lower 4 bits set
not that
how many bits are set IN SUCCESSION
so in a "line"
That would be 3 because 000 and 111 correct?
0b11100110 has 5 bits set, but has 1 line of 3 and 1 line of 2
Either happen -> 3
set bits
ah so the spaces in your original example are just for readability
sorry if i didn't mention that in the message
if you have these tools in your toolbox:
- you know how to get some limit for the amount of bits (you do, it is at most 8)
- you know how to loop and get each bit
- you know how to keep track of state across loop iterations
then you have everything you need to create an algorithm that deals with spans of set bits
num&1 to see current last bit
num>>1 to move the bits right 1 space (thus removing last bit, and second last becomes new last). Save the result of that to use
You'd want to repeat those 2 operations in a loop - until the num becomes 0 (no more bits set to check) and manually keep count of groups
That's the low-memory way.
Memory-intensive way would be to treat it as sequence of characters (so each bit becomes one byte...) and throw it into something like intertools.groupby
alright
makes sense
i'm using this to score connect 4 bitboard positions
i was lead to this SO post
didn't really help since i had zero idea what they meant
Do you want me to show the solution to you?
def solver(v: int) -> int:
max_c = c = 0
while v:
if v & 1:
c+=1
else:
if max_c < c:
max_c = c
c = 0
v >>= 1
return c
You could do v %= 256 or v &= 255 to make sure it only work with 8 bit number tho (the last 8 bit number if exceed)
was groupby suggested?
>>> s = '11100011'
>>> from itertools import groupby
>>> for k, g in groupby(s):
... print(k, len(list(g)))
...
1 3
0 3
1 2
Yes
Memory-intensive way would be to treat it as sequence of characters (so each bit becomes one byte...) and throw it into something like intertools.groupby
where's the source code for itertools.groupby?
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.
