我是靠谱客的博主 风中香烟,最近开发中收集的这篇文章主要介绍Python练习题答案: 行程编码【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战答案1:答案2:答案3:答案4:答案5:答案6:答案7:答案8:答案9:答案10:答案11:,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

行程编码【难度: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道上机题等你来挑战答案1:答案2:答案3:答案4:答案5:答案6:答案7:答案8:答案9:答案10:答案11:的全部内容,希望文章能够帮你解决Python练习题答案: 行程编码【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战答案1:答案2:答案3:答案4:答案5:答案6:答案7:答案8:答案9:答案10:答案11:所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(71)

评论列表共有 0 条评论

立即
投稿
返回
顶部