Unique In Order

https://www.codewars.com/kata/54e6533c92449cc251001667

問題描述

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
For example:

unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
unique_in_order('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
unique_in_order([1,2,2,3,3])       == [1,2,3]

解法

from itertools import groupby
def unique_in_order(iterable):
    return [key for key, value in groupby(iterable)]

題目的要求是將連續相同的字符或者數字取唯一,並不是要把字符串中只要出現兩次以上的都取唯一。groupby函數的功能正好如何這個要求。

items = [1,2,3,1,2,3]
from itertools import groupby
for key, value in groupby(items):
    print(key, list(value), end=' ')
# 1 [1] 2 [2] 3 [3] 1 [1] 2 [2] 3 [3]
for key, value in groupby(sorted(items)):
    print(key, list(value), end=' ')
# 1 [1, 1] 2 [2, 2] 3 [3, 3]

groupby函數只會將連續的相同的元素當做同一個分組,這一特點正好與題目要求符合。


def unique_in_order(iterable):
    result = []
    prev = None
    for char in iterable[0:]:
        if char != prev:
            result.append(char)
            prev = char
    return result
def unique_in_order(iterable):
    res = []
    for item in iterable:
        if len(res) == 0 or item != res[-1]:
            res.append(item)
    return res

unique_in_order = lambda l: [z for i, z in enumerate(l) if i == 0 or l[i - 1] != z]

上面兩個解法很相似,都是遍歷整個list,當前元素和前一個不同則加入結果list中。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章