LoginSignup
13
9
はじめての記事投稿

コーディングテストで便利だと思った機能 (Python)

Posted at

はじめに:point_up:

僕はエンジニアを目指している大学生です。
コーディングテストで使って便利だなと思ったPythonの機能を紹介しようと思います。

便利な機能たち

リストをN個に分割

def split_list(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]
 
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list(split_list(l, 3))
print(result) # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

関数に yield を含めることで、ジェネレータになり反復可能になります。
また、ジェネレータを用いることで、都度必要な分だけ値を生成するので、メモリを効率的に使用できます。

累積和を生成

import itertools

l = [1, 2, 3, 4, 5, 6]

print(itertools.accumulate(l))
# <itertools.accumulate object at 0x10d648140>

print(list(itertools.accumulate(l)))
# [1, 3, 6, 10, 15, 21]

標準ライブラリである itertoolsaccumulate() を使うことで累積和を生成できます。
itertools.accmulate() の引数にはイテラブル(反復可能)なオブジェクトを指定します。
戻り値はイテレータなので、 for を回したり、 list()tuple() を使って綺麗に表現できます。

文字列を逆順に出力

str = "abcdefg"
print(str[::-1]) # "gfedcba"

1つ目の引数(start)と2つ目の引数(end)に何も指定せず、3つ目の引数(step)に -1 を指定することで、末尾から1個ずつ遡って先頭まで要素を取得できます。

参照渡し回避

import copy

hoge = {1:{2:2, 3:3}}
print(id(hoge)) # 140418104920496

fuga = copy.deepcopy(hoge)
print(id(fuga)) # 140418107009728

fuga[1].update({4:4})

print(hoge == fuga) # False

print(hoge) # {1: {2: 2, 3: 3}}

print(fuga) # {1: {2: 2, 3: 3, 4: 4}}

copyモジュールの deepcopy() を使うことで、元のオブジェクトの完全な複製を作成することができるので、copy() と違い参照渡しを回避することが可能です。

重複をなくす

A = [1, 2, 3, 3, 4]
print(set(A)) # {1, 2, 3, 4}

set() を使うことで、指定したオブジェクトはハッシュテーブルになります。
ハッシュテーブルは重複要素を持てないため、重複をなくすことが可能です。
しかし、順序は保持されないです。

おわりに:lifter_tone4:

今回はここまで紹介しました。
まだ紹介してない機能もあるので、次回紹介しようと思います。
エンジニア目指して頑張ります。:lifter_tone1:

13
9
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
13
9