LoginSignup
0
1

More than 3 years have passed since last update.

【python】ペアになる靴下の数を求めるプログラム 

Last updated at Posted at 2020-06-05

【python】ペアになる靴下の数を求めるプログラム

自分用のメモです。

▼設問

  • 任意の数の整数が含まれるlistがある。
  • list内の値は靴下の色の番号を表す。
  • 同じ色が2つ揃うと1セット。
  • セットの数を求める。

url

▼sample input

9
10 20 20 10 10 30 50 10 20

▼sample output

3

▼my answer

def sockMerchant(n, ar):
    pair=0
    for i in set(ar):
        pair += int(ar.count(i)/2)
    return pair

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
    n = int(input())
    ar = list(map(int, input().rstrip().split()))
    result = sockMerchant(n, ar)
    fptr.write(str(result) + '\n')
    fptr.close()

・int()
小数点以下は切り捨て

・countメソッド
オブジェクト.count(i)
オブジェクトの中に、iが何個入っている数を返す。

文字列でも使える。

aaa = "あいうえおあいうえおあい"
aaa.count("あ")


内包表記を使ってシンプルにする

▼my answer(内包表記)

ar=[10,20,20,10,10,30,50,10,20]

def sockMerchant(n, ar):
    return sum([int((ar.count(i))/2) for i in set(ar)])

sockMerchant(9, ar)
  • 内包表記の中で「+=」などの代入は使えない。
  • [ ]の場合、list型が帰ってくる。
  • sum(list)でlistの各要素の合計値が返る
0
1
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
1