4
3

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

CheckiO
 というサイトの練習問題にあった課題。

 記事の題名通りどおり、配列の値がすべて等しいか調べる、という内容である。
 
 初心者の自分は、以下のような解答をした。

python.all_the_same.py
from typing import List, Any

def all_the_same(elements):
    
    #配列の要素数が0の場合
    if len(elements)==0:
        return True
    
    #配列の先頭要素を取得
    lead_element=elements[0]
    
    #要素が等しくない場合Falseを返す
    for element in elements:
        if lead_element!=element:
            return False
    return True

この関数で要件は満たしてはいるのだが、
もっと簡潔なコードはないかと色々調べてみた。

このような時、CheckiO は、
全世界のプログラマの解答が閲覧できるため、便利だ。

備忘録がてら、勉強になったモノをいくつか紹介したいと思う。

1.スライスを使う

python.all_the_same.py

def all_the_same(elements):
    return elements[1:] == elements[:-1]

いちばん驚いた。

list=[1,2,1]

のようなリストを引数として与えた場合
左辺:[2,1]
右辺:[1,2]
で比較し、論理値を返すようになっている。
もちろん同じではないのでFalseが返ってくる。

上記の例だけでは分かり辛いので補足する。

◆計算過程のprintを追加したコード

python.all_the_same.py

def all_the_same(elements):
    #計算過程を出力しておく
    print(str(elements[1:])+"=="+str(elements[:-1]))
    return elements[1:] == elements[:-1]

print(all_the_same([1,2,3,4]))

◆結果

[2,3,4]==[1,2,3]
False

当然ながら結果はFalseだが、

上記のようなスライス記法で、
「配列二つ目から末尾まで」

「配列先頭から末尾一つ手前まで」
を比較できる事がわかる。

スゲェよ旦那ぁ!

2.setとlenを使う

python.all_the_same.py
def all_the_same(elements):
    return len(set(elements)) <= 1

◆setとは
・集合を表すデータ型
・設定時に重複が取り除かれる
・index番号を持たない
・s=set([1,2,3])みたいな感じで作成可能

◆lenとは
・len(変数名 or 文字列)で長さを返す

setの特徴のひとつ、
「重複が取り除かれる」という部分を利用し、
要素数が1以上だった際にFalseを返している。

覚えておくと役に立ちそう。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?