I want to collapse or expand sub-sequences of a list
e.g. ['A', 'B', 'D', 'E', 'H'] -> ['AB', 'DE', 'H']
and vice versa
EDIT: the example above may cause misunderstanding. the following is better:
e.g. ['foo', 'bar', 'wtf'] <-> ['baz', 'wtf']
currently I wrote some ugly code like:
while True:
for i, x in enumerate(s):
if x == 'foo' and s[i+1] == 'bar':
s[i:i+2] = 'baz'
break
else:
break
For people who asking 'why do that thing':
Actually I'm working on a optimizing compiler and this is the peephole part. Writing pattern matching is a little annoying.
P.S. I found the following code works, but a bit ridiculous, why enumerate know our modification?
s = ['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf', 'foo', 'bar', 'wtf']
def collapse():
for i, x in enumerate(s):
if s[i] == 'foo' and s[i+1] == 'bar':
s[i:i+2] = ['baz']
def expand():
for i, x in enumerate(s):
if s[i] == 'baz':
s[i:i+1] = ['foo', 'bar']
collapse()
print s
expand()
print s