ofutonneko

情弱がんばる自分用めも

2020-04-01から1ヶ月間の記事一覧

Python3で階乗を求める

math.factorial(n) を使う。 >>> import math >>> math.factorial(5) 120 >>> math.factorial(10) 3628800 参考: Pythonで階乗、順列・組み合わせを計算、生成 | note.nkmk.me

Python3で2点間の距離を求める

公式の通り書く、でよさそう。 2点を (x1, y1), (x2, y2) とする。 import math math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) distance.euclidean でもできるが遅かった。 from scipy.spatial import distance distance.euclidean((x1, y1), (x2, y2)) numpy…

Python3でリストやタプルの要素の並びを全通り列挙する

リストの要素の並び替えを全通り列挙したい時は、itertools.permutations(l)とすればOK。 タプルでも同様に可。 >>> import itertools >>> l = ['a', 'b', 'c'] >>> for i in itertools.permutations(l): ... print(i) ... ('a', 'b', 'c') ('a', 'c', 'b') …