P111: Modified run-length encoding

修改版游程编码。将P110中的游程编码略加修改,当[N, E]项中N1时,直接简化为E。按照惯例,还是先写测试用例:

from python99.lists.p111 import encode_modified def test_encode_modified(): assert encode_modified([]) == [] assert encode_modified([1, 2, 2, 2, 3, 4, 5, 5]) == [ 1, [3, 2], 3, 4, [2, 5]] assert encode_modified([1, 1, 2, 2, 2, 3, 3, 4, 4, 4]) == [ [2, 1], [3, 2], [2, 3], [3, 4]]

在P110中已经实现了基本款的「游程编码」,现在祇需要在基本款的结果上再加一层处理,将N1[N, E]项转换为E即可。 List comprehension的基本形式为:

[f(x) for e in l]

本例中,f是一个分段函数(piecewise function):

完整的代码实现:

# Modified run-length encoding. # Modify the result of problem 1.10 in such a way that if # an element has no duplicates it is simply copied into the result lists. # Only elements with duplicates are transferred as [N,E] terms. from python99.lists.p110 import encode def encode_modified(l): return [simplify(e) for e in encode(l)] def simplify(term): if term[0] == 1: return term[1] else: return term

results matching ""

    No results matching ""