I have a list of lengths present in a list, like:
a = [1, 3, 4]
Moreover, I have string who's length is exactly the sum of the numbers of a, here 8, looking like that:
s = "01100110"
I am looping over length of a and every time, I would like to have exactly the next n bits present in a. So here, it would be three runs, giving me "0", "110" and "0110".
Is there a very clever idea to do that efficient, for example by slicing? I have some weird complicated ways in my head but search for something more efficient.
Some solution I came up with:
counter_index = 0
counter_sum = 0
for i in range(len(a)):
res = s[counter_sum:counter_sum+a[counter_index]
counter_sum += a[counter_index]
counter_index += 1
print(res)
This approach basically updates the string each time it is sliced so we can get the next value by simply using the values in a
as the index value directly instead of adding it to the existing position value.
a = [1, 3, 4]
s = "01100110"
st = s
i = 0
while i < len(a):
print(st[:a[i]])
st = st[a[i]:]
i+=1
Output
0
110
0110
something like the below is the "slicing" solution to go with
a = [1, 3, 4]
s = "01100110"
offset = 0
for x in a:
print(f'{s[offset: offset+x]}')
offset += x
output
0
110
0110
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With