Python练习问题解答:行程コード【难易度:2级】--景越Pythonプログラミング実例训练キャンプ、1000道上机题などに挑戦

16774 ワード

ストロークコード【難易度: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​