Given a number i.e (0xD5B8
), what is the most efficient way in Python to subset across the bits over a sliding window using only native libraries?
A method might look like the following:
def window_bits(n,w, s):
'''
n: the number
w: the window size
s: step size
'''
# code
window_bits(0xD5B8, 4, 4) # returns [[0b1101],[0b0101],[0b1011],[0b1000]]
window_bits(0xD5B8, 2, 2) # returns [[0b11],[0b01],[0b01],[0b01],[0b10],[0b11],[0b10],[0b00]]
Some things to consider:
- should strive to use minimal possible memory footprint
- can only use inbuilt libraries
- as fast as possible.
- if
len(bin(n)) % w != 0
, then the last window should exist, with a size less thanw
Some of the suggestions are like How to iterate over a list in chunks, which is convert the int using bin
and iterate over as a slice. However, these questions do not prove the optimality. I would think that there are other possible bitwise operations that could be done that are more optimal than running over the bin as a slice (a generic data structure), either from a memory or speed perspective. This question is about the MOST optimal, not about what gets the job done, and it can be considered from memory, speed, or both. Ideally, an answer gives good reasons why their representation is the most optimal.
So, if it is provably the most optimal to convert to bin(x)
and then just manage the bits as a slice, then that's the optimal methodology. But this is NOT about an easy way to move a window around bits. Every op and bit counts in this question.