How can I replace a number of list elements between 2 boundary symbols in a python list -
given list of zeros , boundary elements (ones) there efficient way replace zeros, if less n of them appear between ones?
for n=3: [1,0,0,1,1,1,0,0,0,1,0,0,0] => [1,1,1,1,1,1,0,0,0,1,0,0,0]
some more cases:
[1,0,0,1] => [1,1,1,1] [0,0,1] => [0,0,1] [1,0,0] => [1,0,0]
you can convert list
str
, use replace
method, convert list
:
data = [1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0] n = 3 repl = (("1" + "0" * + "1", "1" + "1" * + "1") in range(1, n)) data_str = "".join(str(i) in data) r in repl: while true: new_str = data_str.replace(r[0], r[1]) if new_str == data_str: break else: data_str = new_str new_data = list(int(s) s in data_str) print(new_data)
this print
[1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0]
it looks little convoluted works fine if have small lists not cause memory issues.
Comments
Post a Comment