Tuesday, October 28, 2008

99 problems - python - 13

Run-length encoding of a list (direct solution). Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem 9, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X

def last_element(lst):
if not lst:
return None
elif type(lst[-1]) == tuple:
return lst[-1][1]
else:
return lst[-1]

def increment_last(lst,x):
if not lst:
lst.append(x)
elif type(lst[-1]) == tuple:
count = lst[-1][0]+1
else:
count = 2

lst[-1] = (count, x)

def encode_frugal(lst):
result = []
for x in lst:
if x == last_element(result):
increment_last(result,x)
else:
result.append(x)

return result

Here's another one that seems a little more verbose than necessary, but that's what I come up with for a first pass.

No comments: