LoginSignup
0
2

More than 5 years have passed since last update.

CheckIO (Python) > Non-unique Elements > 実装してみた

Last updated at Posted at 2017-07-26

リストの中からuniqueでない要素を取り除く処理。
例として、[1, 2, 3, 1, 3]に対して[1, 3, 1, 3]を返す。

v0.1

以下で全assertionをパスしたが、記述が煩雑だ。

from collections import Counter

def checkio(data):
    print(list(data))

    counter = Counter(data)
    pickups = []
    for num, cnt in counter.most_common():
        if cnt > 1:
            pickups.append(num)

    reslist = []
    for elem in data:
        for flt in pickups:
            if elem is flt:
                reslist.append(elem)

    #print(list(reslist))
    return reslist

#Some hints
#You can use list.count(element) method for counting.
#Create new list with non-unique elements
#Loop over original list


if __name__ == "__main__":
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert list(checkio([1, 2, 3, 1, 3])) == [1, 3, 1, 3], "1st example"
    assert list(checkio([1, 2, 3, 4, 5])) == [], "2nd example"
    assert list(checkio([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], "3rd example"
    assert list(checkio([10, 9, 10, 10, 9, 8])) == [10, 9, 10, 10, 9], "4th example"
    print("It is all good. Let's check it now")

suggestionを見てもlist.append()を使うようにとのことなので、あまり改善策は思いつかない。

v0.2

足すのをやめて取り除くことにした。

from collections import Counter

def checkio(data):
    print(list(data))

    counter = Counter(data)
    removes = []
    for num, cnt in counter.most_common():
        if cnt == 1:
            removes.append(num)

    for elem in removes:
        data.remove(elem)

    #print(list(reslist))
    return data

#Some hints
#You can use list.count(element) method for counting.
#Create new list with non-unique elements
#Loop over original list


if __name__ == "__main__":
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert list(checkio([1, 2, 3, 1, 3])) == [1, 3, 1, 3], "1st example"
    assert list(checkio([1, 2, 3, 4, 5])) == [], "2nd example"
    assert list(checkio([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], "3rd example"
    assert list(checkio([10, 9, 10, 10, 9, 8])) == [10, 9, 10, 10, 9], "4th example"
    print("It is all good. Let's check it now")

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2