12
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでリストの要素が全て同じか確かめる

Posted at

誤った情報を公開し続けるのは気が引けたので、書き直しました。
いただいた指摘を反映しつつ、数通りのやり方を書いてみました。

実装

先頭要素を他要素とぶつけて判断する

def map_all(es):
    return all([e == es[0] for e in es[1:]]) if es else False

重複要素を削除した時の要素数で判断する

def set_list(es):
    return len(list(set(es))) == 1
  • esがリストのリストだと実行時エラーになってしまう
  • TypeError: unhashable type: 'list'

先頭要素を他要素とぶつけて判断する(再帰)

def recursive(es):
    return _rec(es, es[0], True) if es else False

def _rec(es, head, acc):
    return _rec(es[1:], head, acc and head == es[0]) if es else acc
  • 前回のreduceでやろうとした事を無理矢理書いてみた
  • 末尾再帰は面倒なのでしていない

先頭要素を複製して比べて判断する

def multi_diff(es):
    return es == [es[0]] * len(es) if es else False
  • テスト中に思いついた

テスト

前回はあまりにも適当だったので、今回はある程度テストしました...

def tests(expected, elements):
    assert map_all(elements) == expected
    assert set_list(elements) == expected
    assert recursive(elements) == expected
    assert multi_diff(elements) == expected

T, F, N = True, False, None

tests(True, [-1])
tests(True, [0])
tests(True, [1])
tests(True, [2])
tests(True, ['T'])
tests(True, [T])
tests(True, [N])

tests(True, [-1, -1])
tests(True, [0, 0])
tests(True, [1, 1])
tests(True, [2, 2])
tests(True, ['T', 'T'])
tests(True, [T, T])
tests(True, [F, F])
tests(True, [N, N])

tests(True, [-1, -1, -1])
tests(True, [0, 0, 0])
tests(True, [1, 1, 1])
tests(True, [2, 2, 2])
tests(True, ['T', 'T', 'T'])
tests(True, [T, T, T])
tests(True, [F, F, F])
tests(True, [N, N, N])


tests(False, [])

tests(False, [0, 1])
tests(False, [1, 0])
tests(False, [0, 2])
tests(False, [1, 2])
tests(False, ['T', 'F'])
tests(False, ['F', 'T'])
tests(False, [T, F])
tests(False, [F, T])
tests(False, [T, N])
tests(False, [N, F])
tests(False, [N, 0])
tests(False, [0, N])

tests(False, [0, 0, 1])
tests(False, [0, 1, 0])
tests(False, [T, F, F])
tests(False, [F, T, F])
tests(False, [F, F, T])
tests(False, [F, T, T])
tests(False, [T, F, T])
tests(False, [T, T, F])
tests(False, [T, T, N])


tests(True, [[]])
tests(True, [[], []])
tests(True, [[], [], []])
tests(True, [[5]])
tests(True, [[5], [5]])
tests(True, [[5], [5], [5]])

tests(False, [[],  [5]])
tests(False, [[3], [5]])
tests(False, [[3], [3, 3]])

おわりに

前回前回と言っているのはこれ、あー恥ずかしい...

12
16
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
12
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?