LoginSignup
0
2

More than 1 year has passed since last update.

Python(書くのが)速いものたち

Last updated at Posted at 2023-01-27

 この記事を読んで感銘を受けたので、「Python 速いものたち」をまとめようと思いましたが、よく考えたら Python は速くないので、(書くのが)速いものたちをまとめました。

文字列操作

  • 文字のカウント count
  • 文字を置き換える replace
    • 正規表現を組み合わせた re.sub は更に強力
  • 区切り文字でリスト化 split
  • 小文字大文字間の変換が容易
import re

s = 'Python is fast to write'
print(s.count('t')) # 4
print(s.replace('t','T')) # PyThon is fasT To wriTe
print(re.sub('[aiueo]','x',s)) # Pythxn xs fxst tx wrxtx
print(s.split(' ')) # ['Python', 'is', 'fast', 'to', 'write']
print(s.upper()) # PYTHON IS FAST TO WRITE

瞬殺できる問題

スライス

  • 部分文字列が書きやすい
  • 末尾を超えた分を自動で省略してくれるのも便利
s = 'Python is fast to write'
print(len(s)) # 23
for i in range(5):
    print(s[:(i+1)*5])
# Pytho
# Python is
# Python is fast
# Python is fast to wr
# Python is fast to write
# 最後の出力は文字列長を超えている点に注意

瞬殺できる問題

itertools

 全探索も順列もこれ一発ですべて解決。

import itertools

a = [0,1,2]
print(*itertools.product(a,repeat=2))
# (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2)
print(*itertools.permutations(a))
# (0, 1, 2) (0, 2, 1) (1, 0, 2) (1, 2, 0) (2, 0, 1) (2, 1, 0)

瞬殺できる問題

複数変数の一括処理

  • a, b, c = list(map(int, input().split(' '))) みたいなやつ。
  • 出力する時も print(a, b, c) でよい。
  • a, b, c = b, c, a みたいにスワップもできる。
a, b, c = 0, 1, 2
print(a, b, c) # 0 1 2
a, b, c = b, c, a
print(a, b, c) # 1 2 0

リスト内包表記

  • リストの変数に一括して処理を行いたい時に便利
    • 1-indexed の入力を 0-indexed に直す
    • 条件に抽出するものだけを残す
    • etc
a = [1,2,3,4,5]
print([i-1 for i in a]) # 0-indexed に直す
# [0, 1, 2, 3, 4]
print([i for i in a if i%2]) # 奇数だけ抽出
# [1, 3, 5]

全体的な注意点

 Python は速く書くことができるが、実行速度が速くなる訳ではない。いかにも $O(1)$ で出来ますよみたいな顔をしているが、実際は $O(N)$ かかっていたりするので注意。

0
2
1

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