LoginSignup
18
17

More than 3 years have passed since last update.

【100 numpy exercises】で"numpy力"を底上げ(1~10問目)

Last updated at Posted at 2020-05-10

paizaのプログラミングスキルチェックをやっているのですが、BランクからAランクに上がるには「numpy」の配列を使いこなせないとダメだなと感じました。

良い練習問題はないものか調べてみたところ「100 numpy exercises」というものがありましたのでチャレンジしてみました。

numpyに関する練習問題100問がJupyter Notebook形式でGitHub上に公開されており、ローカルにダウンロードして問題を解くという形になります。

上記ページの「Clone or download」ボタンから「Download ZIP」を選択してファイルを丸ごとローカルにダウンロードします。

その中に「100_Numpy_exercises.ipynb」というものがあります。これが問題集となりますので、Jupyter Notebookで開きましょう。

最初の説明文を読むと

Run the initialize.py module, then for each question you can query the answer or an hint with hint(n) or answer(n) for n question number.

とあります。
最初のセルの

100_Numpy_exercises.ipynb
%run initialise.py

を実行すると、hint(問題番号)でヒントを、answer(問題番号)で答えが表示されるようです。

さっそく実行してみると「mdutilsというモジュールがない」というエラーになっていまいましたので、
pip install mdutilsでmdutilsというモジュールをインストールしたところ上手くいきました。

では、早速解いていきましょう。まずは1~10問目です。

1. Import the numpy package under the name np (★☆☆)

『numpyをnpという名前でインポートせよ』

これは簡単ですね。

100_Numpy_exercises.ipynb-(1)answer
import numpy as np

answer(1)
と書いて実行してみると、答えが表示されますので、答え合わせしてみましょう。

2. Print the numpy version and the configuration (★☆☆)

『numpyのバージョンと設定を表示せよ』

100_Numpy_exercises.ipynb-(2)answer
print(np.__version__)
np.show_config()

以下のように実行結果が表示されます。

100_Numpy_exercises.ipynb-(2)output
1.18.1
blas_mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\lib', 'C:/ProgramData/Anaconda3\\Library\\include']
blas_opt_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\lib', 'C:/ProgramData/Anaconda3\\Library\\include']
lapack_mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\lib', 'C:/ProgramData/Anaconda3\\Library\\include']
lapack_opt_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\lib', 'C:/ProgramData/Anaconda3\\Library\\include']

show_config()というのは何を確認するために使うんでしょうか…?

3. Create a null vector of size 10 (★☆☆)

『サイズが10で、要素がすべて"0"の一次元配列を作れ』

np.zeros(サイズ)で要素が0の配列を生成することができます。

100_Numpy_exercises.ipynb-(3)answer
Z = np.zeros(10)
print(Z)

実行結果

100_Numpy_exercises.ipynb-(3)output
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

OKですね。

4. How to find the memory size of any array (★☆☆)

『どうすれば配列のメモリサイズがわかるか?』

arrayを配列とすると、
array.sizeで配列の要素数が、array.itemsizeで要素1つあたりのバイト数がわかります。
なので、配列全体のメモリサイズはarray.size*array.itemsizeで求めることができます。

100_Numpy_exercises.ipynb-(4)answer
Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))

実行結果

100_Numpy_exercises.ipynb-(4)output
800 bytes

5. How to get the documentation of the numpy add function from the command line? (★☆☆)

『コマンドラインからnumpyのadd関数のドキュメントをどうやって見ればいいか?』

正式回答では
%run `python -c "import numpy; numpy.info(numpy.add)"`
となっていましたが、

100_Numpy_exercises.ipynb-(5)answer
np.add?

でも見ることができるので、こちらでもいいのではないかと思います。

6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)

『サイズが10で、要素がすべて"0"の一次元配列を作れ。ただし、5つめの要素は"1"であること。』

問題3の応用です。
まずはnp.zeros()ですべて"0"の配列を作ってから、5つめの要素を"1"に書き換えます。

100_Numpy_exercises.ipynb-(6)answer
Z = np.zeros(10)
Z[4] = 1
print(Z)

実行結果

100_Numpy_exercises.ipynb-(6)output
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]

7. Create a vector with values ranging from 10 to 49 (★☆☆)

『10~49までの要素を持つ配列を作れ』

言い換えると、公差が1の等差数列を作ればいいので、np.arange()を使います。

np.arange(start, stop, step)という使い方です。
今回はstart=10、stop=50、step=1となります。
※step=1の場合は、stepは省略しても構いません。

100_Numpy_exercises.ipynb-(7)answer
Z = np.arange(10,50,1)
print(Z)
100_Numpy_exercises.ipynb-(7)output
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]

8. Reverse a vector (first element becomes last) (★☆☆)

『配列を逆にせよ(最初の要素が最後になるように)』

配列を逆順にする関数でもあるのかな?と思ってhintを見てみると…

hint: array[::-1]

なるほど、単にスライスを使って逆順にすればいいんですね。

100_Numpy_exercises.ipynb-(8)answer
Z = np.arange(1,10)
print("Z:", Z)
Z_reverse = Z[::-1]
print("Z_reverse:", Z_reverse)

実行結果

100_Numpy_exercises.ipynb-(8)output
Z: [1 2 3 4 5 6 7 8 9]
Z_reverse: [9 8 7 6 5 4 3 2 1]

9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)

『3行3列の配列(要素は0~8)を作れ』

まず一次元の配列を作ってから、reshape()を使って3行3列に変形するのが簡単かと思います。

100_Numpy_exercises.ipynb-(9)answer
Z = np.arange(0,9)
Z = np.reshape(Z,(3,3)) # Zを3×3の2次元配列の変形
print(Z)

実行結果

100_Numpy_exercises.ipynb-(9)output
[[0 1 2]
 [3 4 5]
 [6 7 8]]

10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)

『[1,2,0,0,4,0]という配列から"0でない"要素のインデックスを見つけろ』

np.nonzero(a) # aはarrayでaという配列のうち0ではない要素のインデックスが返ってきます。

100_Numpy_exercises.ipynb-(10)answer
Z = np.array([1,2,0,0,4,0])
print(np.nonzero(Z))

実行結果

100_Numpy_exercises.ipynb-(10)output
(array([0, 1, 4], dtype=int64),)

ひとまず今回はここまでです。次回は11~20問目を解いていきます。

次回の記事はこちらです。
【100 numpy exercises】で"numpy力"を底上げ(11~20問目)

18
17
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
18
17