def rle_repr(l):
 def add_rle(previous, runlen, result):
  if isinstance(previous, (list, tuple)):
   previous = rle_repr(previous)
  if (runlen > 1):
   result.append(('[%s]*%i' % (previous, runlen)))
  elif (result and ('*' not in result[(-1)])):
   result[(-1)] = ('[%s, %s]' % (result[(-1)][1:(-1)], previous))
  else:
   result.append(('[%s]' % previous))
 iterable = iter(l)
 runlen = 1
 result = []
 try:
  previous = iterable.next()
 except StopIteration:
  return '[]'
 for element in iterable:
  if (element == previous):
   runlen = (runlen + 1)
   continue
  else:
   add_rle(previous, runlen, result)
   previous = element
   runlen = 1
 add_rle(previous, runlen, result)
 return ' + '.join(result)

def rle_repr ( l ) : def add_rle ( previous , runlen , result ) : if isinstance ( previous , ( list , tuple ) ) : previous = rle_repr ( previous ) if ( runlen > 1 ) : result . append ( ( '[%s]*%i' % ( previous , runlen ) ) ) elif ( result and ( '*' not in result [ ( - 1 ) ] ) ) : result [ ( - 1 ) ] = ( '[%s, %s]' % ( result [ ( - 1 ) ] [ 1 : ( - 1 ) ] , previous ) ) else : result . append ( ( '[%s]' % previous ) ) iterable = iter ( l ) runlen = 1 result = [ ] try : previous = iterable . next ( ) except StopIteration : return '[]' for element in iterable : if ( element == previous ) : runlen = ( runlen + 1 ) continue else : add_rle ( previous , runlen , result ) previous = element runlen = 1 add_rle ( previous , runlen , result ) return ' + ' . join ( result )
run-length encode a list into an "eval"-able form example: .