LoginSignup
0
2

More than 3 years have passed since last update.

AtCoder始めました(覚えたPythonコードを備忘まで)

Last updated at Posted at 2019-10-13

このたび、AtCoderを始めました。
始めた今時点での、私のスペックは以下です。

  • Python歴:約半年(=プログラミング言語歴)
  • Python文法はふんわり理解(if,for,while文くらいをなんとなく書ける)
  • Kaggleでコードの書き方は何となく身につけてきた
  • 論理式をもっとスラスラと書きたいというモチベ

まずは、AtCoder Beginners Selectionを解いていきます。そのなかで知らなかったコードを備忘までに残していくのが、こちらの記事です。

文字列の文字の出現個数をカウント

・文字列中の特定文字をカウントするには、count()メソッドを使用する

s = 'supercalifragilisticexpialidocious'
print(s.count('p'))
# 2

参考:https://note.nkmk.me/python-collections-counter/

map関数の使い方

・map(function, sequence)
 ⇒例:map(lambda x: x**2 , list)
・第一引数:関数(またはlambda式)
・第二引数:シーケンス(複数の値を順番に並べたかたまり)
・リスト内包表記で代替OK
 ⇒例:[i*2 for i in list]
・中の要素を見るにはlist関数等で変換が必要

original_list = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
mapped_list = map(lambda x: x**2, original_list)

print(list(mapped_list)) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 上記、リスト内包表記で書くこともできる(こちらのほうがシンプル)
# コメントでご指摘頂きました、ありがとうございます!
print([x**2 for x in original_list]) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

参考:https://www.sejuku.net/blog/24759

min,max関数の使い方

・min,max関数で、list型や複数の要素における最小値・最大値を取得できる

print(min([10, 20, 30, 20, 5, 3]))
print(max('Z', 'A', 'J', 'W'))
# 3
# Z

参考:https://www.python-izm.com/advanced/min_max/

「while True:」による無限ループ

・「while True:」と書くことで無限ループが作れる
・中断させるには、"break"を入れる
・無限ループでしか書けない場合を除き,for ループで書くほうが簡潔でなおかつ速いプログラムになる(コメントでご指摘頂きました、ありがとうございます!)

num = 0
while True:
    print(num)
    num += 1
    if num == 3:
        break
# 0
# 1
# 2


# 「while True:」で書かずとも、以下でシンプルに表現できる
# コメントでご指摘頂きました、ありがとうございます!
num = 0
while num < 3:
    print(num)
    num += 1

参考:https://www.headboost.jp/python-while-true/

アンダーバー( _ )による、変数への不可視の意味づけ

・使わない返り値に変数を割り当てるのはナンセンス
・なので、意識しなくて良い (使われない) という意図を伝える意図でのアンダーバー( _ )表記に
・アンダーバー( _ )から始まる変数は Python で不可視を意味する規約がある
・こうすることで、プログラム的に美しくなる(らしい)

# 返り値は2つだが、2つ目(img2_thresh)しか使わない
_, img2_thresh = cv2.threshold(img2, thresholod, 255, cv2.THRESH_BINARY)

参考:https://qiita.com/ikki8412/items/ab482690170a3eac8c76
   https://www.python.org/dev/peps/pep-0008/

0
2
2

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