i have string representing series of bits:
bit_stream = "10100101011101011101011" # ...(so on)
i need split unevenly sized chunks in repeating pattern. first chunk should length 1, followed chunk of length 8, chunk of length 2, , on until bits exhausted:
result = ["1", "01001010", "11", "1", "01011101", "01", "1"] # ...(so on)
i did other answer posted minute ago didn't use class track state.
import itertools def alternating_size_chunks(iterable, steps): n = 0 step = itertools.cycle(steps) while n < len(iterable): next_step = next(step) yield iterable[n:n + next_step] n += next_step
testing:
>>> test_string = ''.join(random.choice('01') _ in range(50)) >>> print(list(alternating_size_chunks(test_string, (1, 8, 2)))) ['1', '01111010', '01', '1', '00111011', '11', '0', '11010100', '01', '0', '10011101', '00', '0', '11111']
note both these methods (mine , mark's answer) take arbitrary set of lengths (whether it's 1, 8, 2 or else), , work if length of bit stream doesn't precisely add multiple of sum of lengths. (you can see in example ran out of bits , last chunk has five.) may or may not desirable in case, might want check have enough data convert once ready that.
reference: itertools.cycle
Comments
Post a Comment