Python练习题答案: 行程编码【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

行程编码【难度:2级】:

答案1:

from itertools import groupby

def run_length_encoding(s):
    return [[sum(1 for _ in g), c] for c, g in groupby(s)]

答案2:

from itertools import groupby
def run_length_encoding(s):
    return [[len(list(b)), a] for a,b in groupby(s)]

答案3:

def run_length_encoding(s):
  count, prev, lst = 1, '', []
  for c in s:
    if c != prev:
      if prev: lst.append([count, prev])
      count, prev = 1, c
    else: count += 1
  if len(prev) > 0 : lst.append([count, prev])
  return lst​

答案4:

from itertools import groupby
def run_length_encoding(s):
  return [[len(list(g)), k] for k, g in groupby(s)]

答案5:

def run_length_encoding(s):
  from itertools import groupby
  return [[len(list(g)), k] for k, g in groupby(s)]

答案6:

from itertools import groupby

def run_length_encoding(s):
    return [[sum(1 for _ in grp), c] for c, grp in groupby(s)]

答案7:

from itertools import groupby

def run_length_encoding(s):
  return [[len(list(gp)), x] for x, gp in groupby(s)]

答案8:

from re import findall

def run_length_encoding(string):
    return [[len(a), b] for a, b  in findall(r"((.)\2*)", string)]



    #match_runs = r"((.)\2*)"
    #runs = findall(match_runs, string)
    #return [[len(run), char] for run, char in runs]​

答案9:

def run_length_encoding(s):
    result = []
    if s:
        prev = s[0]
        count = 1
        for ind in range(1, len(s)):
            if s[ind] == prev:
                count += 1
            else:
                result.append([count, prev])
                prev = s[ind]
                count = 1
        result.append([count, prev])
    return result
        ​

答案10:

import re
def run_length_encoding(s):
    ls = re.finditer(r'(.)\1*',s)
    t = []
    for i in ls:
        t.append([i.end()-i.start(),i.group()[0]])
    return t​

答案11:

def run_length_encoding(s):
    rle = []
    for i, ch in enumerate(s):
        if i == 0:
            rle.append([1, ch])
        else:
            last_ch = rle[-1][1]
            if last_ch == ch:
                new_count = rle[-1][0] + 1
                rle.pop()
                rle.append([new_count, ch])
            else:
                rle.append([1, ch])
    return rle​

你可能感兴趣的:(Python练习题答案: 行程编码【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战)